实现es5 中 bind()、call()、apply()

bind()

  • 参数的合并
  • 原型继承需要一个中间过度函数
  • this 的 判断
    this instanceof temp ? this : oThis
    有些判断是 this instanceof temp && oThis ? this : oThis || window 不是很懂
    bind() -- mdn
Function.prototype.mybind = function(oThis){
    var self = this;
    var args = Array.prototype.slice.call(arguments,1);
    var temp = function(){};
    var result = function(){
        return self.apply(this instanceof temp
                 ? this
                 : oThis  ,args.concat(Array.prototype.slice.call(arguments)));
    }

    temp.prototype = self.prototype;
    result.prototype = new temp();
    return result;
}

function A(name,age){
    this.name = name;
    this.age = age;
}

var B = A.mybind(null,'bby365');
var b1 = new B(18);

call()

Function.prototype._call = function (context) {
      var context = context || window;
      var args = [];
      for (var i = 1; i < arguments.length; i++) {
        args.push(arguments[i]);
      }

      context.fn = this;

      var res = context.fn(...args);

      delete context.fn;
      return res;
}
// es6 
Function.prototype._call = function (context,...args) {
      var context = context || window;

      context.fn = this;

      var res = context.fn(...args);

      delete context.fn;
      return res;
}

apply()

Function.prototype._apply = function(context,arr){
    var context = context || window;
    context.fn = this;
    var res = context.fn(...arr);
    delete context.fn;
    return res;
}
// 例子
function add(c, d){  
  return this.a + this.b + c + d  
}  
var o = {a:1, b:3} 
add.apply(o, [5, 7]) // 16

总结:call() 和 apply() 返回的是执行的结果,而bind() 返回的是一个新的函数。

你可能感兴趣的:(实现es5 中 bind()、call()、apply())