bind()是ES5中新增的方法,我们可以在ES3中模拟实现bind()方法。
我们在Function.prototype中定义一个b方法,使所有的function可以使用我们自己定义的b方法。
在实现b方法的时候alert(this),会弹出调用b方法的函数,由此可见bind的实现过程是传入你想要被绑定的方法,并且在
函数体内实现闭包返回一个由apply实现的函数调用
ps: function f(y){return this.x+y};
var o={x:1};
var g=f.bind(o);
g(2);//=>3
//通过调用g(x)来调用o.f(x)
我们在Function.prototype中定义一个b方法,使所有的function可以使用我们自己定义的b方法。
Function.prototype.b = function(scope) {
var fn = this;
alert(this)//function f(){alert("nihao");}
return function() {
return fn.apply(scope);
};
}
function f(){alert("nihao");}
var o={};
var g=f.b(o);
g();
在实现b方法的时候alert(this),会弹出调用b方法的函数,由此可见bind的实现过程是传入你想要被绑定的方法,并且在
函数体内实现闭包返回一个由apply实现的函数调用