// 手写 call 函数
Function.prototype.myCall = function(context = window, ...args) {
// 确保调用 myCall 的是函数
if (typeof this !== 'function') {
throw new TypeError('not a function');
}
// 将当前函数设为传入的对象的方法
context.fn = this;
// 调用该方法并获取返回结果
const result = context.fn(...args);
// 删除该方法,避免污染传入的对象
delete context.fn;
return result;
}
// 手写 apply 函数
Function.prototype.myApply = function(context = window, args) {
// 确保调用 myApply 的是函数
if (typeof this !== 'function') {
throw new TypeError('not a function');
}
// 将当前函数设为传入的对象的方法
context.fn = this;
// 调用该方法并获取返回结果
const result = context.fn(...args);
// 删除该方法,避免污染传入的对象
delete context.fn;
return result;
}
// 手写 bind 函数
Function.prototype.myBind = function(context = window, ...args) {
// 确保调用 myBind 的是函数
if (typeof this !== 'function') {
throw new TypeError('not a function');
}
// 保存当前函数
const self = this;
// 返回一个新函数
return function F() {
// 处理当作为构造函数时,this 指向问题
if (this instanceof F) {
return new self(...args, ...arguments);
}
// 普通函数时,直接用 apply 调用
return self.apply(context, args.concat(...arguments));
}
}
// https://www.bilibili.com/video/BV1m54y1q7hc/?spm_id_from=333.337.search-card.all.click&vd_source=1b725373183c977d879b9a72d6329881
console