JS 手撕bind

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;
}
发布了321 篇原创文章 · 获赞 48 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/ferrysoul/article/details/104232378