1、Function.prototype.bind()
bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值,例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj;
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fbound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(this instanceof self ? this : context, args.concat(bindArgs));
}
//实现继承,可以通过 一个空函数进行中转,防止在修改fbound.prototype时,影响 this.prototype
fNOP.prototype = this.prototype;
fbound.prototype = new fNOP();
return fbound;
}
2、实例
var objs = {
a:'a'
}
var obj = {
a:'aaa',
func:function(b,c){
console.log(arguments)
console.log(this.a,b,c)
}
}
obj.func.bind2(objs,'b','c')('d')
// a b c