Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
const key = Symbol();
Object.defineProperty(ctx, key, {
value: this,
enumerable: false,
});
const r = ctx[key](...args);
delete ctx[key];
return r;
};
let bob = {
name: "aa",
age: 18,
};
function fn() {
console.log("this:", this);
}
fn.myCall(bob, 1, 2);
Function.prototype.myBind = function (ctx, ...args) {
const fn = this;
return function (...newArgs) {
if (new.target) {
return new fn(...args, ...newArgs);
}
return fn.apply(ctx, [...args, ...newArgs]);
};
};