call、apply、bind

call

定义:调用一个对象的一个方法,以另一个对象替换当前对象,传递多个参数

Person.prototype.sayHi=function (x,y) {
      console.log("您好啊:"+this.sex);
      return 1000;
    };
    var per=new Person(10,"男");
    function Student(name,sex) {
      this.name=name;
      this.sex=sex;
    }
    var stu=new Student("小明","人妖");
    var r2=per.sayHi.call(stu,10,20);

apply

定义:应用某一对象的一个方法,用另一个对象替换当前对象,apply传递多个参数的时候第二个参数需要传递一个数组

Person.prototype.sayHi=function (x,y) {
      console.log("您好啊:"+this.sex);
      return 1000;
    };
    var per=new Person(10,"男");
    function Student(name,sex) {
      this.name=name;
      this.sex=sex;
    }
    var stu=new Student("小明","人妖");
    var r1=per.sayHi.apply(stu,[10,20]); 

call/bind区别

call 和 apply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同

bind

bind也能改变this的指向,返回一个修改过的函数,但该函数不会被执行

function f1(x, y) {
      console.log((x + y) + ":=====>" + this.age);
    }
function Person() {
     this.age = 1000;
   }
   Person.prototype.eat = function () {
     console.log("这个是吃");
   };
   var per = new Person();

   var ff = f1.bind(per, 10, 20);
  • applay、call和bind的却别在于前者立即执行,后者在需要的时候执行

实现一个call函数

Function.prototype.myCall = function (context) {
  var context = context || window
  // 给 context 添加一个属性,这里的this就是new出来的实例化对象
  context.fn = this
  // 将 context 后面的参数取出来
  var args = [...arguments].slice(1)
  var result = context.fn(...args)
  // 删除 fn
  delete context.fn
  return result
}

实现一个apply函数

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this
  var result
  // 需要判断是否存储第二个参数
  // 如果存在,就将第二个参数展开
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}

豌豆资源搜索网站https://55wd.com 广州vi设计公司http://www.maiqicn.com

实现一个bind函数

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}
原文地址:https://www.cnblogs.com/qianxiaox/p/13696041.html