JS如何使用父函数的参数调用函数内部的函数?

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

我需要典型案例的帮助,但我不知道如何在没有诸如 for .. in .. 或 forEach 之类的肮脏事情的情况下做到这一点。 所以,我有一个带有一些方法和 bool 字段的对象,它显示是否需要打印日志。类似的东西:

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

显然,会有很多相同的代码,在每个方法上重复:

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

最佳做法是将此代码移动到新方法中:

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

并调用此方法而不是重复 if... passage:

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

但是如果我需要在一个日志中记录未知数量的参数怎么办,比如:

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

所以,问题是:无论发送了多少参数,我如何在我的函数中调用 console.log?

为什么不在调用日志函数之前使用 x 参数格式化您的消息,以便您只有一个格式化的字符串来记录?

使用 Function#apply along with arguments 对象以传递给父函数的参数调用函数。

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

您还可以使用带参数的 spread operator,这样您就不必调用 .apply

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