「跟着渡一学前端」手写call函数
完整代码
Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
const fn = this;
const key = Symbol();
Object.defineProperty(ctx, key, {
value: fn,
enumerable: false,
});
const r = ctx[key](...args);
delete ctx[key];
return r;
}
function method(a,b){
console.log('args',a,b);
console.log('this',this);
}
method.myCall(1,2,3);
具体分析
-
写在哪?——写到函数原型(
Function.prototype)上 -
有哪些参数?
-
对第一个参数(即对需要绑定的
this参数)进行处理 -
绑定this

浙公网安备 33010602011771号