const globalThis = typeof window !== 'undefined' ? window : global;
Function.prototype.myCall = function (context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Type error');
}
context = context || global;
const key = Symbol('key');
context[key] = this;
const res = context[key](...args);
delete context[key];
return res;
}
Function.prototype.myApply = function (context = globalThis, args = []) {
if (typeof this !== 'function') {
throw new TypeError('Type error');
}
context = context || global;
const key = Symbol('key');
context[key] = this;
const res = context[key](...args);
delete context[key];
return res;
}
Function.prototype.myBind = function (context = globalThis, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Type error');
}
let self = this;
return function F() {
if (this instanceof F) {
return new self(...args, ...arguments);
}
return self.apply(context, [...args, ...arguments]);
}
}
标签:function,...,const,context,bind,args,call,key,apply
From: https://www.cnblogs.com/laiyaoweb/p/17088243.html