2017-06-19 195 views
0

我需要典型案例的帮助,但我不知道如何做到这一点,没有像.. in ..或forEach这样的脏东西。 所以,我有一个方法和布尔字段显示的对象,需要打印日志或不。类似的东西:JS如何使用父函数的参数调用函数内部的函数?

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函数中使用相同的参数,无论他们发了多少钱?

回答

1

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

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

您还可以使用spread operator带参数,这使得它,这样你就不用调用.apply

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

谢谢!有用! – Teo

1

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

+0

没有的事,我需要的,但不错的主意太/ – Teo