JavaScript调用()及适用于()与bind()的? [英] Javascript call() & apply() vs bind()?
问题描述
我已经知道适用
和呼叫
是哪一组类似的功能这个
(函数的情况下)。
I already know that apply
and call
are similar functions which setthis
(context of a function).
不同的是用我们发送的参数(手动VS数组)的方式
The difference is with the way we send the arguments (manual vs array)
问:
但是,当我应该使用绑定()
方法?
But when should I use the bind()
method ?
var obj = {
x: 81,
getX: function() { return this.x; }
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
推荐答案
使用 .bind()
如果您想要进行功能以后具有一定的上下文中被调用的,有用的在事件。使用 .CALL()
或。适用()
当你想立即调用功能可按和修改的背景。
Use .bind()
when you want that function to later be called with a certain context, useful in events. Use .call()
or .apply()
when you want to invoke the funciton immediately, and modify the context.
呼叫/应用立即调用函数,而绑定
返回一个函数,当以后执行将有正确的上下文调用原有的功能设置。这样你就可以保持异步回调和事件的背景。
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. This way you can maintain context in async callbacks, and events.
我这个做了很多的:
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.
};
我的node.js为我想通过一个成员方法异步回调广泛使用它,但仍希望的背景下是启动异步操作的实例。
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.
有一个简单,幼稚的实现绑定将是这样的:
A simple, naive implementation of bind would be like:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
有更给它(如通过其他的参数),但你可以阅读更多关于它,看到了真正实施的在MDN 。
There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.
希望这有助于。
这篇关于JavaScript调用()及适用于()与bind()的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!