AlJo
AlJo

Reputation: 171

How to pass ALL of a variable number of args to ANOTHER function that accepts a variable number of args?

One function that accepts a variable # of args needs to pass the entire set of args into another function that also accepts a variable # of args, for example (the following does NOT work):

debugConsole : function(msg) {
    if(this.isDebugOn()) {
        console.log(arguments); // does not work, prints "[object Arguments]"
    }
}

I need this so the string substitution feature of console.log() works, i.e.

var myObject = {name: "John Doe", id: 1234};

// should print "obj = [object Object]"
this.debugConsole("myObject = %o", myObject); 
// should print "name: John Doe, ID: 1234"
this.debugConsole("name: %s, ID: %i", myObject.name, myObject.id);

Upvotes: 2

Views: 51

Answers (1)

Chris Hayes
Chris Hayes

Reputation: 12050

Use Function.apply:

debugConsole : function(msg) {
    if(this.isDebugOn()) {
        console.log.apply(console, arguments);
    }
}

Upvotes: 2

Related Questions