包装JavaScript回调重新定义;这";

包装JavaScript回调重新定义;这";,javascript,Javascript,我知道JavaScript中的call和apply,但我目前遇到以下情况 我使用的是基准测试js,它的API定义如下: .on(eventType, listener) foo = function() { this.suite.on('start', this.onStart); } 所以我会这样做,例如: /* Register the onStart callback */ suite.on('start', onStart); 我的onStart函数将被调用,以便this==

我知道JavaScript中的
call
apply
,但我目前遇到以下情况

我使用的是基准测试js,它的API定义如下:

.on(eventType, listener)
foo = function() {
   this.suite.on('start', this.onStart);
}
所以我会这样做,例如:

/* Register the onStart callback */
suite.on('start', onStart);
我的
onStart
函数将被调用,以便
this===suite

如何才能定义
onStart
参数之一

我的代码是这样的:

.on(eventType, listener)
foo = function() {
   this.suite.on('start', this.onStart);
}
我希望我的
onStart
函数引用
foo


有什么建议吗?

您可以通过将此
包装到函数中,将其传递给
onStart

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

我更喜欢传递它而不是使用
bind
,因为IE 8和更低版本不支持
bind

您可以调用
Function.prototype.bind
来创建部分应用程序/当前函数

.bind()
将上下文作为第一个参数,并且以下所有传入的参数都将用作绑定函数调用的形式参数

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

foo
的引用现在将作为第一个参数提供给
onStart()

使用
bind
覆盖
这个
并插入参数。这将丢失由Benchmarkjs传递给它的
onStart
的参数。@salvatoreivine:哇,忘了这一点。有点难看,但这很管用。