关键是要搞懂闭包,和函数this指向。写出这三个其中的一个,另外的迎刃而解。
Function.prototype.myCall = function (context, ...args) {
// 如果没有指定context,让context指向globalThis全局对象,
// 如果context不是对象,将其强转为对象
context =
context === null || context === void 0 ? globalThis : Object(context);
let s = Symbol("fn"); // 定义一个符号防止覆盖context原本的属性
Object.defineProperty(context, s, {
value: this,
enumerable: false,
});
return context[s](...args); // 将参数数组展开调用
};
Function.prototype.myApply = function (context, args) {
context =
context === null || context === void 0 ? globalThis : Object(context);
const fn = Symbol(); // 定义一个符号防止覆盖context原本的属性
Object.defineProperty(context, fn, {
value: this,
enumerable: false,
});
return context[fn](...args); // 将参数数组展开调用
};
Function.prototype.myBind = function (context, ...args) {
const fn = this;
return function (...params) {
return fn.myApply(context, [...args, ...params]);
};
};