console.log.call.apply

174 阅读1分钟
const result = console.log.call.call.call.call.apply((a)=>a,[1,2])
console.log(result)

console.log.__proto__ === Function.prototype

console.log.call === Function.prototype.call

console.log.call.call.call.call === Function.prototype.call

const result = Function.prototype.call.apply((a)=>a,[1,2])

----------------------------
// 一个简化的 call 方法的实现
if (!Function.prototype.myCall) {
  Function.prototype.myCall = function(context = window, ...args) {
    // context 参数是你希望 'this' 指向的对象
    // 如果没有提供 context(或者传入的是 null/undefined),默认将 this 指向全局对象(浏览器中是 window)

    // 为 context 创建一个唯一的属性以存储当前函数(避免与 context 原有的属性冲突)
    const fnSymbol = Symbol();
    context[fnSymbol] = this; // 'this' 指向调用 myCall 的函数对象

    // 调用函数并传入参数,使用展开运算符将参数列表传递给函数
    const result = context[fnSymbol](...args);

    // 删除临时添加的属性
    delete context[fnSymbol];

    // 返回函数调用的结果
    return result;
  };
}
-----------------------------

result = 2

为什么输出是2:在这个特定的调用中,apply将数组[1, 2]作为参数传递给call方法。根据call方法的工作原理,第一个参数(在这个例子中是1)被视为this的值,而剩余的参数(在这个例子中是2)被传递给调用的函数。然而,由于箭头函数不绑定this,1这个值被忽略,箭头函数直接接收到2作为它的参数a,并返回它。