js中 call apply bind的區(qū)別

最近在回顧以前的知識,整理下這三位this指向的使用。
在 JavaScript 中,call()、apply()、bind() 是函數(shù)原型上的方法,它們可以用來改變函數(shù)的 this 指向。

  1. call() 方法用于調用一個函數(shù),并將第一個參數(shù)作為 this 的值,后續(xù)參數(shù)作為函數(shù)的參數(shù)。
  2. apply() 方法與 call() 類似,但第二個參數(shù)是一個數(shù)組,該數(shù)組包含要傳遞給函數(shù)的參數(shù)。
  3. bind() 方法創(chuàng)建一個新的函數(shù),并將第一個參數(shù)作為 this 的值,后續(xù)參數(shù)作為新函數(shù)的參數(shù)。

下面是一個使用這些方法的示例代碼片段:

function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}

const person = { name: 'John Doe' }; // 假設這是一個對象

// 使用 call() 方法調用函數(shù),并設置 this 為 person 對象
greet.call(person, 'Hello', '!'); // 輸出 'Hello, John Doe!'

// 使用 apply() 方法調用函數(shù),并設置 this 為 person 對象
greet.apply(person, ['Hi', '.']); // 輸出 'Hi, John Doe.'

// 使用 bind() 方法創(chuàng)建一個新的函數(shù),并設置 this 為 person 對象
const boundGreet = greet.bind(person, 'Hey', '?');
boundGreet(); // 輸出 'Hey, John Doe?'

在這個示例中,我們定義了一個名為 greet 的函數(shù),它接受兩個參數(shù):greetingpunctuation。然后,我們定義了一個名為 person 的對象,其中包含一個 name 屬性。

我們使用 call() 方法調用 greet 函數(shù),并將 person 對象作為 this 的值,同時傳遞 'Hello''!' 作為參數(shù)。這會輸出 'Hello, John Doe!'

我們還使用 apply() 方法調用 greet 函數(shù),并將 person 對象作為 this 的值,同時傳遞一個包含 'Hi''.' 的數(shù)組作為參數(shù)。這會輸出 'Hi, John Doe.'。

最后,我們使用 bind() 方法創(chuàng)建一個新的函數(shù) boundGreet,并將 person 對象作為 this 的值,同時傳遞 'Hey''?' 作為參數(shù)。然后,我們調用 boundGreet 函數(shù),它會輸出 'Hey, John Doe?'

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容