JavaScript call、apply 和 bind 的區別

Shiv Yadav 2023年10月12日
  1. JavaScript 中的 function.call() 方法
  2. JavaScript 中的 function.apply() 方法
  3. JavaScript 中的 bind() 方法
JavaScript call、apply 和 bind 的區別

今天我們將解釋 apply()call()bind() 方法之間的區別。使用這些 JavaScript 技術,你可以修改給定函式的 this 的值。

JavaScript 中的 function.call() 方法

function.call() 方法呼叫該函式並允許你使用逗號一次傳送一個引數。這裡提到的例子,this 指的是 person 物件,而 this.nameworker1worker2 的名稱。

例子:

let worker1 = {name: 'Oli', email: 'oli@gmail.com'};
let worker2 = {name: 'Kp', email: 'kp@hotmail.com'};

function invite(text) {
  console.log(`${text} ${this.name}`);
}
invite.call(worker1, 'Hello Upwork');
invite.call(worker2, 'Hello Upwork');

輸出:

"Hello Upwork Oli"
"Hello Upwork Kp"

執行程式碼

JavaScript 中的 function.apply() 方法

你可以使用 function.apply() 方法呼叫具有提供的 this 值和作為陣列提供的引數的函式。apply()call() 方法相似,但不是單獨的引數,而是將函式的引數作為陣列。

例子:

let worker1 = {name: 'Oli', email: 'oli@gmail.com'};
let worker2 = {name: 'Kp', email: 'kp@hotmail.com'};
function invite(text, text2) {
  console.log(`${text} ${this.name}, ${text2}`);
}
invite.apply(worker1, ['Hello', 'How are you?']);
invite.apply(worker2, ['Hello', 'How are you?']);

輸出:

"Hello Oli, How are you?"
"Hello Kp, How are you?"

執行程式碼

JavaScript 中的 bind() 方法

bind() 方法建立了一個新函式,該函式接受此陣列和任意數量的引數。當你想稍後使用特定上下文(例如事件)呼叫函式時,請使用它。

例子:

let worker1 = {name: 'Oli', email: 'leo@gmail.com'};
let worker2 = {name: 'Kp', email: 'nat@hotmail.com'};
function invite(text) {
  console.log(`${text} ${this.name}`);
}
let helloOli = invite.bind(worker1);
let helloKp = invite.bind(worker2);
helloOli('Hello');
helloKp('Hello');

輸出:

"Hello Oli"
"Hello Kp"

執行程式碼

以下示例是 Bind 實現。

例子:

Function.prototype.bind = function(context) {
  var func = this;
  return function() {
    func.apply(context, arguments);
  };
};

callapply 是可以互換的。你可以選擇是陣列還是逗號分隔的引數列表更方便。Bind 和其他的不一樣。

它每次都返回一個新函式。如示例所示,我們可以使用 Bind 來柯里化函式。

我們可以從一個簡單的 hello 操作中建立一個 "helloOli""helloKp"。當我們不知道它們何時會被觸發但它們將在什麼上下文中時,它可以用於事件。

作者: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn

相關文章 - JavaScript Methods