Search code examples
javascriptscopeargumentscallbind

JS how to call a function inside a function with arguments of a parent function?


I need help with typical case but I have no idea how to do this without dirty things like for .. in .. or forEach. So, i have an object with some methods and bool field which shows, need to print log or not. Something like that:

var sender = {
  showLogs: true,
  doSomething: function(){
    "do something";
    if (this.showLogs)
      console.log("Sender do something")
  }
}

Obviously, there will be a lot of same code, repeating on every method:

if(this.showLogs)
  console.log("Sender do x");

Best practice is to move this code into new method:

..
log: function(message){
  if (this.showLogs)
    console.log(message)
}
..

And call this method instead of repeating if... passage:

  ..
  doSomething: function(){
    "do something";
    this.log("Sender do something");
  }
 ..

But what if I need to log unknown quanity of arguments in one log, like:

this.log("Start at: ", start time,", Value send: ", data);

So, the question is: how can i call console.log inside my function with the same parameters, no matter how much of them was sended?


Solution

  • Use Function#apply along with arguments object to call a function with the arguments that were passed to the parent function.

    log: function(message){
      if (this.showLogs)
        console.log.apply(null,arguments);
    }
    

    You can also use the spread operator with arguments, which makes it so you do not have to call .apply

    log: function(message){
      if (this.showLogs)
        console.log(...arguments);
    }