封装bind方法

思路:

  1.返回一个函数体

  2.改变this的指向

  3.传递参数

Function.prototype.bindTo = function(){
    //传递过来的第一个参数
    var that = arguments[0];
    //获取到剩余的参数
    var arr = Array.prototype.slice.call(arguments).slice(1);

    var _this = this;


    var fn = function(){
        var newThis = this instanceof fn?this : that
        _this.apply(newThis,arr);
    }


    //继承
    fn.prototype = {
        constructor:fn,
        __proto__:this.prototype
    }

    return fn;
}

猜你喜欢

转载自www.cnblogs.com/shy0113/p/10550509.html