call apply bind

差异

bind 和 call 传参方式一样,但是bind返回的是一个函数,绑定this,且可传递预置参数
call 和 apply 传参方式不一样,apply接收两个参数,第二个参数是一个参数数组
这三个都是用来重定义 this 这个对象的,下面的例子可以简单看出几个方法的不同

var student = {
  name: "高三学生",
  age:18,
  sayHi: function (province,city) {
    console.log("HI~我是" + this.name +",今年"+this.age+ ",来自" + province+city);
  },
};
var san = {
  name: "张三",
  age :20
};
student.sayHi.call(san,'湖南','长沙')
student.sayHi.apply(san,['湖南','长沙'])
student.sayHi.bind(san,'湖南','长沙')()
// 三个打印出来
// HI~我是张三,今年20,来自湖南长沙

实现这三个方法

Function.prototype.apply = function(context = window, args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type Error');
  }
  const fn = Symbol('fn');
  context[fn] = this;

  const res = context[fn](...args);
  delete context[fn];
  return res;
}

Function.prototype.call = function(context = window, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type Error');
  }
  const fn = Symbol('fn');
  context[fn] = this;

  const res = context[fn](...args);
  delete context[fn];
  return res;
}

Function.prototype.bind = function(context, ...args) {
  if (typeof this !== 'function') {
    throw new Error("Type Error");
  }
  // 保存this的值
  var self = this;

  return function F() {
    // 考虑new的情况
    if(this instanceof F) {
      return new self(...args, ...arguments)
    }
    return self.apply(context, [...args, ...arguments])
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 夜莺2517阅读 127,912评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 11,911评论 1 6
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 12,765评论 28 53
  • 兔子虽然是枚小硕 但学校的硕士四人寝不够 就被分到了博士楼里 两人一间 在学校的最西边 靠山 兔子的室友身体不好 ...
    待业的兔子阅读 7,550评论 2 9

友情链接更多精彩内容