【问题标题】:JS how to call a function inside a function with arguments of a parent function?JS如何使用父函数的参数调用函数内部的函数?
【发布时间】:2017-11-21 20:09:37
【问题描述】:

我需要典型案例的帮助,但我不知道如何在没有诸如 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... 段落:

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

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

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

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

【问题讨论】:

    标签: javascript scope arguments call bind


    【解决方案1】:

    使用Function#applyarguments 对象来调用带有传递给父函数的参数的函数。

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

    您还可以将spread operator 与参数一起使用,这样您就不必调用.apply

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

    【讨论】:

      【解决方案2】:

      为什么不在调用 log 函数之前用 x 参数格式化你的消息,这样你就只有一个格式化的 String 来记录?

      【讨论】:

      • 不是我需要的东西,但也是个好主意/
      猜你喜欢
      • 1970-01-01
      • 2013-06-23
      • 2018-10-21
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多