gpt4 book ai didi

javascript - 包装重新定义 "this"的 JavaScript 回调

转载 作者:行者123 更新时间:2023-11-29 15:43:48 25 4
gpt4 key购买 nike

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

我正在使用 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 的引用。

有什么建议吗?

最佳答案

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

.bind()context 作为第一个参数,所有后续传入的参数将用作绑定(bind)函数的形式参数调用。

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

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

关于javascript - 包装重新定义 "this"的 JavaScript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14896365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com