call 方法的实现
Function.prototype.call = function (context, ...args) {
const ctx = context || window;
let i = 0;
let funcName = '';
while(true) {
if (!(`__CALL__${i}` in ctx)) {
funcName = `__CALL__${i}`;
break;
}
i++;
}
ctx[funcName] = this;
const res = ctx[funcName](...args);
delete ctx[funcName];
return res;
};
apply 方法的实现
Function.prototype.apply = function (context, args) {
const ctx = context || window;
let i = 0;
let funcName = '';
while(true) {
if (!(`__CALL__${i}` in ctx)) {
funcName = `__CALL__${i}`;
break;
}
i++;
}
ctx[funcName] = this;
const res = ctx[funcName](...args);
delete ctx[funcName];
return res;
};
bind 方法的实现
Function.prototype.bind = function (context, ...bindArgs) {
let ctx = JSON.parse(JSON.stringify(context)) || window;
ctx.func = this;
return function (...args) {
bindArgs = bindArgs || [];
args = bindArgs.concat(args);
return ctx.func(args);
}
}