天天看點

JS 手撕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;
}