JS 手撕bind
原创
©著作权归作者所有:来自51CTO博客作者wx5c4a6751206d9的原创作品,请联系作者获取转载授权,否则将追究法律责任
bind本质:返回一个函数,且可传入多个参数。
A = Animal.bind(Cat, name);
a = new A(age);
// ES5
function myBind1(context){// Cat
if(typeof this !== "function") throw new Error("not Function")
var self = this;
var args1 = Array.prototype.slice.call(arguments, 1);
var Fn = function(){
var args2 = Array.prototype.slice.call(arguments);
return self.apply(this instanceof context? this: context, args1.concat(args2))
}
var Fmiddle = function(){};
Fmiddle.prototype = this.prototype;
Fn.prototype = new Fmiddle();
return Fn;
}
// ES6
function myBind2(context, ...args1) {// Cat
var self = this;
var Fn = function (...args2) {
return self.apply(this instanceof context ? this : context, args1.concat(args2))
}
var Fmiddle = function () { };
Fmiddle.prototype = this.prototype;
Fn.prototype = new Fmiddle();
return Fn;
}