js自定义call apply bind
Function.prototype.myCall=function(context,...args){ context=context==null ? globalThis : Object(context); const fnKey=Symbol('fn'); context[fnKey]=this; const result=context[fnKey](...args); delete context[fnKey]; return result; } Function.prototype.myApply=function(context,args=[]){ context=context==null ? globalThis : Object(context);
const fnKey=Symbol('fn'); context[fnKey]=this; const result=context[fnKey](...args); delete context[fnKey]; return result }
Function.prototype.myBind = function(context, ...bindArgs) {
const originalFunc = this;
return function boundFunc(...callArgs) {
// 判断是否作为构造函数调用 (new boundFunc())
if (new.target) {
// 作为构造函数时,忽略绑定的 this
return new originalFunc(...bindArgs, ...callArgs);
} else {
// 普通调用,使用绑定的 context
const actualContext = context==null? globalThis : Object(context);
const fnKey = Symbol('fn');
actualContext[fnKey] = originalFunc;
const result = actualContext[fnKey](...bindArgs, ...callArgs);
delete actualContext[fnKey];
return result;
}
};
};
function logCall(...msg){ console.log(msg) } function logApply(msg){ console.log(msg) } logApply.myApply({},['this is mycall',4444]); logCall.myCall({},'22',66); const aa=logCall.myBind({},'55555','6666'); aa('9999')

浙公网安备 33010602011771号