最近在回顧以前的知識,整理下這三位this指向的使用。
在 JavaScript 中,call()、apply()、bind() 是函數(shù)原型上的方法,它們可以用來改變函數(shù)的 this 指向。
-
call()方法用于調用一個函數(shù),并將第一個參數(shù)作為this的值,后續(xù)參數(shù)作為函數(shù)的參數(shù)。 -
apply()方法與call()類似,但第二個參數(shù)是一個數(shù)組,該數(shù)組包含要傳遞給函數(shù)的參數(shù)。 -
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ù):greeting 和 punctuation。然后,我們定義了一個名為 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?'。