若函式沒有明確的擁有者,例如 makeArray("one", "two"),在非嚴格模式下,this 通常會指向全域物件,在瀏覽器中就是 window。
function makeArray(arg1, arg2) {
return [this, arg1, arg2];
}
若函式作為物件方法呼叫,例如 arrayMaker.make("one", "two"),this 會指向 arrayMaker。
若使用 new 呼叫函式,this 會指向新建立的物件。因此建議使用大寫字母命名建構函式,提醒自己在呼叫時加上 new。
理解 these 三種規則,多數 this 相關的錯誤都能避免。