包装JavaScript回调重新定义;这";
我知道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==
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:哇,忘了这一点。有点难看,但这很管用。