手动实现一个apply

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

关键步骤,在 context 上调用方法,触发 this 绑定为 context
和 call 基本类似,但是需要判断是否包含参数 args

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

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

name = "234";
person.call({ name: "test" }, ["111", "222"]);
person.myCall(null, ["111", "222"]);

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