Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS如何在具有父函数参数的函数中调用函数?_Javascript_Scope_Arguments_Call_Bind - Fatal编程技术网

Javascript JS如何在具有父函数参数的函数中调用函数?

Javascript JS如何在具有父函数参数的函数中调用函数?,javascript,scope,arguments,call,bind,Javascript,Scope,Arguments,Call,Bind,我需要典型案例的帮助,但我不知道如何做到这一点没有肮脏的东西,如。。在里面或forEach。 所以,我有一个带有一些方法和布尔字段的对象,显示是否需要打印日志。诸如此类: var sender = { showLogs: true, doSomething: function(){ "do something"; if (this.showLogs) console.log("Sender do something") } } 显然,会有很多相同的代码,

我需要典型案例的帮助,但我不知道如何做到这一点没有肮脏的东西,如。。在里面或forEach。 所以,我有一个带有一些方法和布尔字段的对象,显示是否需要打印日志。诸如此类:

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)
}
..
如果。。。段落:

  ..
  doSomething: function(){
    "do something";
    this.log("Sender do something");
  }
 ..
但如果我需要在一个日志中记录未知数量的参数,比如:

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

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

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

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

请与一起使用对象调用具有传递给父函数的参数的函数

log: function(message){
  if (this.showLogs)
    console.log.apply(null,arguments);
}
您还可以使用with参数,这样您就不必调用
。apply

log: function(message){
  if (this.showLogs)
    console.log(...arguments);
}
与对象一起使用可使用传递给父函数的参数调用函数

log: function(message){
  if (this.showLogs)
    console.log.apply(null,arguments);
}
您还可以使用with参数,这样您就不必调用
。apply

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

不是我需要的东西,也是好主意/