2013-02-15 54 views
3

我知道關於callapply在JavaScript中,但我目前堅持以下情況。包裝重新定義「this」的JavaScript回調

我使用Benchmarkjs,它有這樣定義的API:

.on(eventType, listener) 

所以我會做,比如:

/* Register the onStart callback */ 
suite.on('start', onStart); 

onStart函數將被調用這樣this === suite

我該怎麼做才能定義onStartarguments之一?

我的代碼是這樣的:

foo = function() { 
    this.suite.on('start', this.onStart); 
} 

我想我onStart功能有一個參考foo

有什麼建議嗎?

+3

使用'bind'來覆蓋'this'並插入參數。 – 2013-02-15 14:01:53

回答

1

您可以調用Function.prototype.bind創建部分應用程序/ curried函數。

.bind()上下文作爲第一參數和在參數的所有下面通過將用作形式參數用於綁定函數調用。

suite.on('start', this.onStart.bind(this, foo)); 

foo參考現在將提供給onStart()非常的第一個參數。

0

您可以將this轉換爲onStart,方法是將其封裝在函數中。

foo = function() { 
    this.suite.on('start', function(arguments){onStart(arguments, this)}); 
} 

我喜歡它傳遞而不是使用bind,由於bind不受IE 8和下部支撐。

+0

這將失去由Benchmarkjs傳遞給它的'onStart'的參數。 – 2013-02-15 14:06:24

+0

@SalvatoreIovene:哎喲,忘了那個。 有點醜,但這個工程。 – Cerbrus 2013-02-15 14:07:19