Function.prototype.myCall = function (ctx, ...args) {
if (ctx === null)
ctx = window;
else if (typeof ctx !== 'object')
ctx = new Object(ctx);
const fn = Symbol();
ctx[fn] = this;
const rst = ctx[fn](...args);
Reflect.deleteProperty(ctx, fn);
return rst;
}
Function.prototype.myApply = function (ctx, args) {
if (ctx === null)
ctx = window;
else if (typeof ctx !== 'object')
ctx = new Object(ctx);
const fn = Symbol();
ctx[fn] = this;
const rst = ctx[fn](...args);
Reflect.deleteProperty(ctx, fn);
return rst;
}
Function.prototype.myBind = function (ctx, ...args) {
const slef = this;
return function (...args1) {
return slef.apply(ctx,[...args,...args1])
}
}
function fn (a, b) {
console.log(this);
return a + b;
}
const rst = fn.myCall({
name: 'yihua'
}, 2, 3)
console.log(rst);
const rst1 = fn.myApply({
name: 'yihua'
},[3,4])
console.log(rst1);
const fn2 = fn.myBind({name:'yihua',age:18},4)
const rst2 = fn2(5);
console.log(rst2);