Use .bind()
when you want that function to later be called with a certain context, useful in events.
(当您希望以后在特定上下文中调用该函数时,请使用.bind()
,在事件中很有用。)
Use .call()
or .apply()
when you want to invoke the function immediately, and modify the context. (若要立即调用该函数并修改上下文,请使用.apply()
.call()
或.apply()
。)
Call/apply call the function immediately, whereas bind
returns a function that, when later executed, will have the correct context set for calling the original function.
(调用/应用立即调用该函数,而bind
返回一个函数,该函数稍后执行时,将具有正确的上下文集来调用原始函数。)
This way you can maintain context in async callbacks and events. (这样,您可以在异步回调和事件中维护上下文。)
I do this a lot:
(我经常这样做:)
function MyObject(element) {
this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);
};
MyObject.prototype.onClick = function(e) {
var t=this; //do something with [t]...
//without bind the context of this function wouldn't be a MyObject
//instance as you would normally expect.
};
I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.
(我在Node.js中将它广泛用于异步回调,我想为其传递成员方法,但仍希望上下文成为启动异步操作的实例。)
A simple, naive implementation of bind would be like:
(一个简单,简单的bind实现是:)
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN .
(它还有更多的功能(就像传递其他args一样),但是您可以阅读更多有关它的内容,并查看MDN上的实际实现。)
Hope this helps.
(希望这可以帮助。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…