手动实现一个call

本文最后更新于:2023年3月19日 晚上

关键是在 context 上调用方法,触发 this 绑定为 context

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function.prototype.myCall = function (context, ...args) {
// 关键步骤,在 context 上调用方法,触发 this 绑定为 context,使用 Symbol 防止原有属性的覆盖
const key = Symbol("key");
context[key] = this;
const res = context[key](args);
delete context[key];
return res;
};

function person(...args) {
console.log(this.name);
console.log(args);
}

person.call({ name: "test" }, "111", "222");
person.myCall({ name: "test" }, "111", "222");

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!