call,apply,bind

相同作用:

都是为了改变this指向而存在的。

区别:

  • 这三个方法接受的第一个参数都是要绑定的this指向
  • apply的第二个参数是一个数组,即把要传入函数的参数放在数组内传入;而call是把需要的参数按顺序传递进去
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
  • bind则是返回一个待执行的新函数, 当新函数执行的时候改变了this的指向,但这个函数不会马上执行。

call的简单实现

Function.prototype.myCall = function(context,...args){
context = context || window;
context.fn = this;
let res = context.fn(...args);
delet context.fn;
return res;
}

apply的简单实现

Function.prototype.myApply = function(context,...args){
context = context || window;
contect.fn = this;
let res = context.fn(...args);
delet context.fn;
return res;
}

bind的简单实现

Function.prototype.bindNew = function (context, ...args) {
  return (...newArgs) => this.apply(context, [...args, ...newArgs]);
};

// test
const test = {
  name: "fy",
  showName: function (last) {
    console.log(this.name + " is " + last);
  },
};
test.showName("handsome"); // fy is handsome
test.showName.bindNew({ name: "Mr.fy" })("handsome");
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容