JavaScript 的函式都是物件,因此也會繼承「Object.prototype」的所有屬性與方法,也可以有專屬於自己的方法。
常見的函式方法包含「bind()」、「call()」跟「apply()」,用來讓函式內容的「this」指向指定物件,若未指定,則「this」將指向視窗物件(window object)。
舉例來說,如果我們創建一個名為「Japan」的物件,內有「name」、「capital」、「area」、「inAsia」四種屬性,另設有「hostOlympics()」這個函數:
let Japan = {
name: "Japan",
capital: "Tokyo",
area: 378000,
inAsia: true
}
function hostOlympics(mascot, designer){
console.log(this);
console.log(this.capital + " is hosting Olympics.");
console.log(mascot + " is the mascot.");
console.log("It is designed by " + designer + ".");
}
hostOlympics("Miraitowa","Ryo Taniguchi");
上述程式碼執行結果如下:
第三行跟第四行都沒有問題,但為何第一行跟第二行會出現錯誤呢?
這是因為第三行與第四行都是直接取用函數參數「(“Miraitowa”,”Ryo Taniguchi”)」,但第一行及第二行都有個「this」,這裡的「this」跟「Japan」物件沒有任何關係、指的是視窗物件(window object),視窗物件中並沒有「hostOlympics()」方法,因此顯示結果為「undefined」。
若要讓「hostOlympics()」裡面的「this」指向「Japan」物件,可透過下列三種方法:
bind()-回傳函式,要用另一個變數接住
let Japan = {
name: "Japan",
capital: "Tokyo",
area: 378000,
inAsia: true
}
function hostOlympics(mascot,designer){
console.log(this);
console.log(this.capital + " is hosting Olympics.");
console.log(mascot + " is the mascot.");
console.log("It is designed by " + designer + ".");
}
let Tokyo2020 = hostOlympics.bind(Japan);
Tokyo2020("Miraitowa","Ryo Taniguchi");
call()-直接執行函式,參數可直接輸入
let Japan = {
name: "Japan",
capital: "Tokyo",
area: 378000,
inAsia: true
}
function hostOlympics(mascot,designer){
console.log(this);
console.log(this.capital + " is hosting Olympics.");
console.log(mascot + " is the mascot.");
console.log("It is designed by " + designer + ".");
}
hostOlympics.call(Japan, "Miraitowa","Ryo Taniguchi");
apply()-直接執行函式,參數用「陣列」形式輸入
let Japan = {
name: "Japan",
capital: "Tokyo",
area: 378000,
inAsia: true
}
function hostOlympics(mascot,designer){
console.log(this);
console.log(this.capital + " is hosting Olympics.");
console.log(mascot + " is the mascot.");
console.log("It is designed by " + designer + ".");
}
hostOlympics.apply(Japan, ["Miraitowa","Ryo Taniguchi"]);
不管是用「bind()」、「call()」還是「apply()」,顯示結果都相同: