Function 是 JavaScript 的絕對核心。它同時肩負了 procedure、method、constructor,甚至 class 與 module 的角色。在傳統物件導向語言裡這是四件不同的事、四套不同語法;在 JavaScript 中,全部由 function 一肩承擔,靠三種不同的呼叫模式來區分。
function hello(username) {
return "hello, " + username;
}
hello("Keyser Söze"); // "hello, Keyser Söze"
當函數被賦值給某個物件的成員,它的身分就從「函數」變成了「方法」:
var obj = {
hello: function() { return "hello, " + this.username; },
username: "Hans Gruber"
};
obj.hello(); // "hello, Hans Gruber"
關鍵在於:是「呼叫」這個動作決定 this 綁到哪個物件。obj1.hello() 把 this 綁到 obj1,obj2.hello() 就綁到 obj2。一句話記住:誰呼叫,this 就指向誰。
正因為規則如此,下面的寫法也成立:
function hello() { return "hello, " + this.username; }
var obj1 = { hello: hello, username: "Gordon Gekko" };
obj1.hello(); // "hello, Gordon Gekko"
var obj2 = { hello: hello, username: "Biff Tannen" };
obj2.hello(); // "hello, Biff Tannen"
但在普通函數裡使用 this 有其風險:一旦被直接呼叫,this 會落到全域物件(瀏覽器上就是 window),這種行為既不明確也沒意義。因此 ES5 提供了嚴格模式:
function hello() {
"use strict";
return "hello, " + this.username;
}
hello(); // TypeError: Cannot read property 'username' of undefined
讓錯誤提早爆掉,總比埋一個難找的 bug 好。
var func = function() { alert(this); };
var o = {};
o.fn = func;
alert(o.fn === func); // true —— 是同一個函數
func(); // [object Window]
o.fn(); // [object Object]
函數相同,但呼叫方式不同,this 就不同:直接呼叫時 this 指向 window,作為方法呼叫時指向 o。
第三種模式,是把 function 當成 constructor 使用。
var Person = function() { this.name = "小平果"; };
var p = new Person();
逐步拆解:
結論:建構函數中的 this 就是當前物件。
// 回傳物件:return 照原意生效
var ctr = function() {
this.name = "趙曉虎";
return { name: "牛亮亮" };
};
var p = new ctr();
alert(p.name); // "牛亮亮"
// 回傳基本型別:return 被忽略,仍然回傳 this
var ctr2 = function() {
this.name = "趙曉虎";
return "牛亮亮";
};
var p2 = new ctr2();
alert(p2); // [object Object]
alert(p2.name); // "趙曉虎"
規則是:回傳物件則保留原意;回傳數字、字串、布林等基本型別,或完全沒有 return,一律回傳 this。
function User(name, passwordHash) {
this.name = name;
this.passwordHash = passwordHash;
}
var u = new User("sfalken", "0ef33ae791068ec64b502d6cb0191387");
u.name; // "sfalken"
與函數呼叫、方法呼叫不同,constructor 會傳入一個新物件並綁定到 this,最後把它作為回傳值;建構函數本身的職責就是初始化這個物件。
var Coder = function(nick){ this.nick = nick; };
var coder = Coder('casper'); // 少了 new!
console.log(coder.nick); // undefined
console.log(window.nick); // "casper" —— 值被寫到 window 上了
var coder2 = new Coder('casper'); // 加上 new
console.log(coder2.nick); // "casper"
這個錯誤看起來很初階,發生率卻不低,因為少了 new 完全不會報錯,只是靜靜地把屬性掛到全域物件上。
var Coder = function(nick){
if (!(this instanceof Coder)) {
return new Coder(nick); // 沒用 new,就自己補一次
}
this.nick = nick;
};
思路很單純:若 this 不是當前建構函數的實例,就強制重跑一次。缺點是類名寫死了,改名要改兩處。想只改一處,可以用 arguments.callee:
var Coder = function(nick){
if (!(this instanceof arguments.callee)) {
return new arguments.callee(nick);
}
this.nick = nick;
};
提醒:ES5 嚴格模式禁用 arguments.callee,若已全面採用嚴格模式,請改用具名函數表達式來達到同樣效果。
以上就是本文的全部內容,希望對你理解函數呼叫、方法呼叫與建構函數呼叫有所幫助。