bind()的作用与call()和apply()一样,都是可以改变函数运行时上下文,区别是call()和apply()在调用函数之后会立即执行,而bind()方法调用并改变函数运行时上下文后,返回一个新的函数,供我们需要时再调用
因此可以考虑用apply来实现bind的功能,直接上代码
Function.prototype.bind = function (that) {
if (typeof this !== 'function') { // 判断调用bind方法的对象的类型是否为函数
throw new TypeError('only function can use bind');
}
var args = [].slice.call(arguments, 1); // 调用bind传递进来的参数,除去第一个参数obj test.bind(obj, pram)
var fToBind = this;
var fNop = function() {}; // 用来复制this的原型
var fBound = function () {
// this instanceof fBound ? this : that 主要是为了适应 new fBound()时,this指向自身实例
// 这也是为什么使用bind后,再new得到的函数,原先绑定的对象会失效
// args.concat([].slice(arguments)) args 为调用bind时传入的参数,arguments 为执行 fBound传入的参数,然后拼接在一起
/* 举个栗子
this.a = 20;
var o = {
foo: function() {
console.log(111);
console.log(this.a);
},
bar(){ // ES6的写法,包含箭头函数都有这个问题
console.log(222);
}
}
var f = o.foo.bind({a: 30});
new f(); // 111 undefined => new 对bind失效,导致this不为{a: 30},而是foo{}
*/
return fToBind.apply(this instanceof fBound ? this : that, args.concat([].slice(arguments)));
}
fNop.prototype = this.prototype;// 继承原函数的原型,这里不直接fBound.prototype = this.prototype,是为了避免两个原型指向同一个对象,相互影响
fBound.prototype = new fNop();// 利用中介函数实现原型的继承
return fBound;
}