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

2018-06-12  本文已影响0人  bby365

bind()

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() 返回的是一个新的函数。

上一篇 下一篇

猜你喜欢

热点阅读