call、apply和bind的原生实现

61 阅读2分钟
//   let obj = {
//     name: 'csj',
//     fn: function (age, sex) {
//       console.log(this.name, age, sex);
//     },
//   };
//   obj.fn(11,22);  // csj 11 22

  let person = {
    name: "Abiel",
  };
  function target() {
     
  }
  function sayHi(age, sex) {
    console.log(this,this.name, age, sex);
  }
  sayHi.newApply(person, [25, "男"]); // Abiel 25 男   target是对象,this指向该对象
  sayHi.apply(target, [25, "男"]); // "target" 25 "男"  target是函数,this指向该函数的prototype原型的constructor,constructor中有name属性,是函数的名字

call:

Function.prototype.newCall = function (context, ...parameter) {
context.fn = this;
context.fn(...parameter);
delete context.fn;
};
let person = {
name: "Abiel",
};
function sayHi(age, sex) {
console.log(this.name, age, sex);
}
sayHi.newCall(person, 25, "男"); // Abiel 25 男

这样我们基本上实现了call的功能,但是还是存在一些隐患和区别。
当对象本身就有fn这个方法的时候,就有大问题了。
当call传入的对象是null的时候,或者其他一些类型的时候,函数会报错。 升级版本:

Function.prototype.newCall = function(context, ...parameter) {
  if (typeof context === 'object') {
    context = context || window // 排除null
  } else {
    context = Object.create(null) // 不是引用类型对象数组null的情况
  }
  let fn = Symbol()
  context[fn] = this
  context[fn](...parameter); // 立即执行
  delete context[fn]  // 删除context对象的fn属性
}
let person = {
  name: 'Abiel'
}
function sayHi(age,sex) {
  console.log(this.name, age, sex);
}
sayHi.newCall (person, 25, '男'); // Abiel 25 男

实现了call之后,apply也是同样的思路。
apply实现:

Function.prototype.newApply = function(context, parameter) {
    if (!Array.isArray(parameter)) {
      throw new Error("newApply的第二个参数只能是数组哦");
   }
  if (typeof context === 'object') {
    context = context || window
  } else {
    context = Object.create(null)
  }
  let fn = Symbol()
  context[fn] = this
  context[fn](...parameter);
  delete context[fn]
}

bind

bind也是函数的方法,作用也是改变this执行,同时也是能传多个参数。与call和apply不同的是bind方法不会立即执行,而是返回一个改变上下文this指向后的函数,原函数并没有被改变。并且如果函数本身是一个绑定了 this 对象的函数,那 apply 和 call 不会像预期那样执行。

Function.prototype.bind = function (context,...innerArgs) {
  var me = this
  return function (...finnalyArgs) {
    return me.call(context,...innerArgs,...finnalyArgs)
    // return me.apply(context, [...innerArgs, ...finnalyArgs])
  }
}
let person = {
  name: 'Abiel'
}
function sayHi(age,sex,...args) {
  console.log(this, this.name, age, sex, args);
}
let personSayHi = sayHi.bind(person, 25)
personSayHi('男',66)
// {name: "Abiel"} "Abiel" 25 "男" [66]

参考:

www.zhihu.com/question/47…

github.com/Abiel1024/b…