我们知道call和apply是相似的函数,主要是改变this(function的上下文(context));
比如:
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 只是绑定this,需要使用()调用函数
call 和apply则直接改变this,立即调用函数;
不给call传参都可以直接调用函数;
var sData = 'Wisen';
function display(){
console.log('sData value is %s ', this.sData);
}
display.call(); // sData value is Wisen
.bind()是在你知道特定的上下文,需要将该上下文绑定在function上,并在之后调用的时候使用。在events中使用最多。
.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.
};
bind的简单实现是这样的:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
他们都是将原函数的this,指向到特定的function或者obj;只是立即执行与之后执行的区别:
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传入的是数组:
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"