js 如何实现bind

192 阅读1分钟
  • one
Function .prototype.bindSelf= function(context){
    var that = this;
    return function(){
        that.apply(context)
    }
}
  • Two
Function . prototype . bind2 = function(context){
    var that = this;
    //获取参数
    var args = Array.prototype.slice.call(arguments,1);
    return function(){
        var bindArgs = Array.prototype.slice.call(arguments)
        that .apply(context,args.concat(bindArgs))
    }
}
  • Three
Function.prototype.bind = function(context){
    var that = this;
    var args = Array.prototype.slice.call(arguments,1);
    var Fun = function(){}
    var Func = function(){
        var bindArgs = Array.prototype.slice.call(arguments);
        that.apply(this instanceof that ? this : context,bindArgs)
    }
    Fun.prototype = this.prototype;
    Func.prototype = new Fun();
    return Func;
}