執行x.call.call發生了什麼(JS)

call方法(Function.prototype.call)是用來改變某個方法被調用時的this指向。

官方描述:使用一個指定的 this 值和單獨給出的一個或多個參數來調用一個函數

首先,call的常規用法(如下):

const obj = {
  name: 'test-object',
};

function helper() {
  console.log('output');
  console.log(this);
  console.log('name: ', this?.name);
  console.log('args: ', arguments);
}

helper.call(obj, 0, 1, 2);

然後,我們回到主題,看看 x.call.....call 這種用法,該如何理解。

直接看下方代碼吧(特別是註釋部分)

function foo() {
  console.log('foo -> this: ', this);
}

function fake() {
  console.log('fake -> this: ', this);
}

/**
 * 1. foo.call(fake) 性質過程描述
 * 其等同於:
 * const key = Symbol('foo');
 * fake[key] = foo;
 * fake[key]();
 * delete fake[key];
 */

/**
 * 2. foo.call.call 可以將其理解爲:
 * const call = foo.call;
 * 因爲 foo.call === Function.prototype.call,
 * 所以 call === Function.prototype.call。
 * 故,
 * call.call(fake, true);
 * 等同於(參考 1):
 * fake.call(true);
 * 所以,最後的輸出爲:'fake -> this:  [Boolean: true]'
 */

foo.call.call(fake, true);
// output: 'fake -> this:  [Boolean: true]'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章