代码高亮测试

白天 1712994542842

JS > 代码高亮测试

首先进行分析,call 的调用方式是 fn.call(thisArg, arg1, arg2, ...),它会立即调用一次,所以我们需要做的事情就是:

  1. 获取需要执行的函数(就是 this,因为 call 的调用都是 fn.call(),fn 是一个函数)

  2. 对 thisArg 进行转换成对象类型(防止传入的是一个非对象类型),这个 thisArg 就是需要绑定的 this

  3. 调用需要被执行的函数(通过给 thisArg 增加方法属性)

Function.prototype.myCall = function (thisArg, ...args) {
    let fn = this;
    thisArg = thisArg !== null && thisArg !== undefined ' Object(thisArg) : window;
    thisArg.fn = fn;
    const result = thisArg.fn(...args);
    delete thisArg.fn;
    return result;
};