this 大概是 JavaScript 裡被討論最多、也最容易搞混的關鍵字。關鍵在於:this 是動態決定的,它在函數「執行」的那一刻才被確定,而不是在宣告的時候。同一個函數用不同方式呼叫,this 指向的對象可以完全不同。
以下依序說明六種典型情境。
函數如果是掛在物件上被呼叫,this 就指向該物件:
var john = { firstName: "John" } function func() { alert(this.firstName + ": hi!") } john.sayHi = func john.sayHi() // this = john
但要注意:一旦把方法從物件上「取出來」單獨賦值給變數再呼叫,它就退化成普通函數呼叫,this 會變成 window,在嚴格模式下則是 undefined。
func() function func() { alert(this) // [object Window](嚴格模式下為 undefined) }
ES5 的規範其實要求這種情況 this 應為 undefined,但瀏覽器基於相容性大多仍指向 window。想讓 this 正確傳遞,() 前面必須是「引用類型」,例如 obj.a 或 obj['a'],不能是其他東西。
這裡還藏著一個常見的坑:物件方法內部再定義的函數,會以「函數模式」觸發,this 預設又回到 window。解法是用 call 把 this 綁回去:
var numbers = { numberA: 5, numberB: 10, sum: function() { console.log(this === numbers); // => true function calculate() { console.log(this === numbers); // => false return this.numberA + this.numberB; } return calculate(); } }; numbers.sum(); // => NaN var numbers2 = { numberA: 5, numberB: 10, sum: function() { function calculate() { return this.numberA + this.numberB; } return calculate.call(this); // 用 call 修正 this 指向 } }; numbers2.sum(); // => 15
用 new 建立物件時,this 的變化可以拆成三步:先建立一個空的 this = {},接著執行函數本文並挂上屬性與方法,最後把這個 this 回傳。
function Animal(name) { this.name = name this.canWalk = true } var animal = new Animal("beastie") alert(animal.name)
若建構函數明確回傳一個物件,那麼 this 會指向回傳的那個物件:
function Animal() { this.name = 'Mousie'; this.age = '18'; return { name: 'Godzilla' } } var animal = new Animal() console.log(animal.name) // Godzilla console.log(animal.age) // undefined
另外別忘了寫 new,否則它就只是普通函數呼叫,this 指向 window,屬性會被掛到全域物件上:
function Vehicle(type, wheelsCount) { this.type = type; this.wheelsCount = wheelsCount; return this; } var car = Vehicle('Car', 4); car === window // => true
這是最能體現 JavaScript 彈性的地方。func.call(obj, arg1, arg2, ...) 的第一個參數會成為 this,其餘參數則依序傳入函數:
function Animal(type, legs) { this.type = type; this.legs = legs; this.logInfo = function() { console.log(this === myCat); // => true console.log('The ' + this.type + ' has ' + this.legs + ' legs'); }; } var myCat = new Animal('Cat', 4); setTimeout(myCat.logInfo.bind(myCat), 1000); var john = { firstName: "John", surname: "Smith" } function func(a, b) { alert( this[a] + ' ' + this[b] ) } func.call(john, 'firstName', 'surname') // "John Smith"
apply 唯一的差別是第二個參數必須以陣列形式傳入:
func.call(john, 'firstName', 'surname') func.apply(john, ['firstName', 'surname'])
它們也很常用於 ES5 的「類繼承」中呼叫父層建構函數:
function Runner(name) { console.log(this instanceof Rabbit); // => true this.name = name; } function Rabbit(name, countLegs) { console.log(this instanceof Rabbit); // => true Runner.call(this, name); // 借用父層建構函數 this.countLegs = countLegs; } var myRabbit = new Rabbit('White Rabbit', 4); myRabbit; // { name: 'White Rabbit', countLegs: 4 }
和 call/apply 不同,bind() 不會立刻執行,而是回傳一個「this 已被預先固定」的新函數,可以延後呼叫:
var numbers = { array: [3, 5, 10], getNumbers: function() { return this.array; } }; var boundGetNumbers = numbers.getNumbers.bind(numbers); boundGetNumbers(); // => [3, 5, 10] var simpleGetNumbers = numbers.getNumbers; simpleGetNumbers(); // => undefined 或 在嚴格模式下拋錯
bind 建立的是一條永久的上下文鏈:即使事後再用 call 或 apply 傳入不同的 this,也不會生效,重複 bind 同樣無效。唯一的例外是搭配 new 呼叫時,this 會被新建立的物件取代,但這並不是推薦的用法。
箭頭函數不會建立自己的 this,它沿用「定義時所在外層函數」的 this,而且一次綁定後無法更改:
var numbers = [1, 2]; (function() { var get = () => { console.log(this === numbers); // => true return this; }; console.log(this === numbers); // => true get(); // => [1, 2] get.call([0]); // => [1, 2] get.apply([0]); // => [1, 2] get.bind([0])(); // => [1, 2] }).call(numbers);
正因為 this 是靜態的,所以不要用箭頭函數來定義物件方法:
function Period (hours, minutes) { this.hours = hours; this.minutes = minutes; } Period.prototype.format = () => { console.log(this === window); // => true return this.hours + ' hours and ' + this.minutes + ' minutes'; }; var walkPeriod = new Period(2, 30); walkPeriod.format(); // => 'undefined hours and undefined minutes'
判斷 this 指向時,可以依序問自己:是不是用 new 呼叫?是不是用 call/apply/bind 指定過?是不是作為某個物件的方法呼叫?都不是的話,就是普通函數呼叫,this 落在全域物件或 undefined。箭頭函數則自成一套規則,永遠沿用外層。
延伸閱讀:Four scents of "this"、Gentle explanation of 'this' keyword in JavaScript,以及後者的中文版《JavaScript This 之謎》。