我已经知道apply
和call
是设置this
(函数上下文)的类似函数。
区别在于我们发送参数的方式(手动vs数组)
问题:
但是什么时候应该使用bind()
方法呢?
var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
JSbin
前一阵子我在函数对象,函数调用,调用/应用
和绑定
之间创建了这个比较:
.bind
允许您现在设置this
值,同时允许您将来执行函数,因为它返回一个新的函数对象。
当您希望以后在某个上下文中调用该函数时,请使用.bind()
,这在事件中很有用。如果要立即调用函数,请使用.call()
或.apply()
,并修改上下文。
call/apply立即调用函数,而bind
返回一个函数,当以后执行时,该函数将为调用原始函数设置正确的上下文。这样您就可以在异步回调和事件中维护上下文。
我经常这样做:
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中广泛使用它来进行异步回调,我希望为这些回调传递一个成员方法,但仍然希望上下文是启动异步操作的实例。
简单,朴素的bind实现如下:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
它还有更多的内容(像传递其他参数一样),但是您可以阅读更多关于它的内容,并在MDN上看到真正的实现。
希望这能帮上忙。
它们都将此附加到函数(或对象)中,区别在于函数调用(见下文)。
call将其附加到函数中,并立即执行该函数:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"
bind将其附加到函数中,需要单独调用它,如下所示:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world"); // output: Jim Smith says hello world"
或者像这样:
...
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc(); // output: Jim Smith says hello world"
apply与call类似,只是它采用一个类似数组的对象,而不是一次列出一个参数:
function personContainer() {
var person = {
name: "James Smith",
hello: function() {
console.log(this.name + " says hello " + arguments[1]);
}
}
person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"