2693.使用自定义上下文调用函数
链接:2693.使用自定义上下文调用函数
难度:Medium
标签:
简介:增强所有函数,使其具有 callPolyfill 方法。该方法接受一个对象 obj 作为第一个参数,以及任意数量的附加参数。obj 成为函数的 this 上下文。附加参数将传递给该函数(即 callPolyfill 方法所属的函数)。
题解 1 - typescript
- 编辑时间:2023-05-23
- 执行用时:64ms
- 内存消耗:43.9MB
- 编程语言:typescript
- 解法介绍:利用原型链挂载this。
declare global {
interface Function {
callPolyfill(context: Record<any, any>, ...args: any[]): any;
}
}
Function.prototype.callPolyfill = function (context: any, ...args): any {
const temp = Symbol();
context.__proto__[temp] = this;
const res = context[temp](...args);
delete context.__proto__[temp];
return res;
};