MDN一句话介绍bind:
bing() 方法会创建一个新函数。当这个新函数被调用时,bind()的第一个参数将作为它运行时的this, 之后的一序列参数将会在传递的实参前传入它的参数。
由此我们可以得出bind函数的两个特点:
- 返回一个函数
- 可以传入参数
var foo = {
value: 1
};
function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
bar(); // undefiend undefiend undefiend
var barBind = bar.bind(foo);
barBind(); // 1 undefiend undefiend
barBind('jump', 18);// 1 jump 18
bind 特点
一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略。
也就是说当bind返回的函数作为构造函数的时候, bind时指定的this值会失效,但是参数仍然生效。
var value = 2;
var foo = {
value: 3
};
var bar = function(name,age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var barBind = bar.bind(foo,'jump',18);
var bindObj = new barBind();
console.log(bindObj);// undefiend jump 18
- 注意: 尽管在全局和foo中都声明了value值, 最后依然返回了undefiend, 说明绑定的this失效了, 因为这个时候的this已经指向了bindObj。