原生js封装call、apply、bind方法

   call方法

  首先要了解call方法,在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。call方法接收两个参数,一个是函数运行的作用域(this),另一个是函数传入的参数

  var obj = {
    name:'aaa',
    age:18,
    say:function(a, b, c) {
      console.log(this.name, a, b, c);
    }
  }
  var obj2 = {
    name:'bbb',
  }
  Function.prototype.myCall(that, ...argu) {
    that = that || window; //如果没有传默认window
    var fn = this; //say函数
    var fnName = this.name + new Date() * 1; //保证say函数的唯一性
    that[fnName] = fn; //在that对象上添加一个函数
    that[fnName](...argu); //执行函数
    delete that[fnName]; //用完就删除
  }
  obj.say.myCall(obj2, 1, 2, 3);

   apply方法

   var obj = {
    name:'aaa',
    age:18,
    say:function(a, b, c) {
      console.log(this.name, a, b, c);
    }
  }
  var obj2 = {
    name:'bbb',
  }
 Function.prototype.myApply(that, argu) {
    that = that || window; //如果没有传默认window
    var fn = this; //say函数
    var fnName = this.name + new Date() * 1; //保证say函数的唯一性
    that[fnName] = fn; //在that对象上添加一个函数
    that[fnName](...argu); //执行函数
    delete that[fnName]; //用完就删除
  }
  obj.say.myApply(obj2, [1, 2, 3]);

   bind方法

  var obj = {
    name:'aaa',
    age:18,
    say:function(a, b, c) {
      console.log(this.name, a, b, c);
    }
  }
  var obj2 = {
    name:'bbb',
  }
 Function.prototype.myBind(that, ...argu) {
    var self = this;
      return function() {
        var newP = argu.concat(...arguments);
        self.myApply(that, newP);
      }
  }
  obj.say.myBind(obj2, [1, 2, 3]);

你可能感兴趣的:(原生js封装call、apply、bind方法)