我知道這個主題已經被寫過千千萬萬次,但還是想把 this 的各種情況整理成一篇,當成自己的總結歸納。在 JS 裡,this 的上下文變化莫測,出 bug 時常常一頭霧水;其實只要分清楚不同情境下的執行規則就夠了。
first. 瀏覽器:
console.log(this); // Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
second. Node:
console.log(this); // global
結論:全域作用域中的 this 指向當前全域物件——瀏覽器是 Window,Node 是 global。
function test() { console.log(this); }; test(); // Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
直接呼叫的函式屬於全域呼叫,this 指向全域物件。
加上嚴格模式後:
'use strict'; function test() { console.log(this); }; test(); // undefined
這麼做是為了消除 JS 一些不嚴謹的行為。實務上更推薦包進立即執行函式裡,避免污染全域:
(function (){ "use strict"; console.log(this); })(); // undefined
var obj = { name: 'qiutc', foo: function() { console.log(this.name); } } obj.foo(); // 'qiutc'
此時 this 指向該物件。也可以先定義函式再掛上去:
function test() { console.log(this.name); } var obj = { name: 'qiutc', foo: test } obj.foo(); // 'qiutc'
因為在 JS 裡函式也是物件,test 只是個指向函式的名稱,foo = test 之後兩者指向同一個函式。
但如果把方法指派給變數再呼叫:
var obj = { name: 'qiutc', foo: function() { console.log(this); } } var test = obj.foo; test(); // Window
test 此時只是一個函式參照,與 obj 已無關係,因此被當成普通函式呼叫,this 回到全域。
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); setTimeout(this.foo, 1000); } } obj.foo2();
兩次印出來的 this 不同:第一次在 foo2 裡直接印,指向 obj,這沒問題;但 setTimeout 裡的 this.foo 卻指向了全域物件。原因很單純——setTimeout 也是個函式,我們把 this.foo 當參數傳進去,等同做了一次 fun = this.foo,執行時跑的是 fun(),早已和 obj 無關。這個問題在所有非同步回呼裡都會遇到。
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); var _this = this; setTimeout(function() { console.log(this); // Window console.log(_this); // Object {name: "qiutc"} }, 1000); } } obj.foo2();
先用 _this 把當下的 this 存起來,回呼裡改用 _this,就指向原本那個物件了。
'use strict'; function foo() { console.log(this); } setTimeout(foo, 1); // window
明明開了嚴格模式,卻還是印出全域物件?並不是嚴格模式失效了。實際上 setTimeout 在呼叫傳入函式時,若該函式沒有指定 this,會隱式注入全域上下文,等同 foo.apply(window) 而非 foo()。若傳入時已用 bind 指定,就不會被注入,例如 setTimeout(foo.bind(obj), 1)。
function Person(name) { this.name = name; console.log(this); } var p = new Person('qiutc'); // Person {name: "qiutc"}
加上 new 時,this 指向新建立的實例;若當普通函式呼叫,則一樣指向全域:
function Person(name) { this.name = name; console.log(this); } var p = Person('qiutc'); // Window
差別只在於「怎麼呼叫」。
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); setTimeout(() => { console.log(this); // Object {name: "qiutc"} }, 1000); } } obj.foo2();
箭頭函式內的 this,是「定義時所在」的物件,而不是「使用時所在」的物件。仔細拆解一下:執行 obj.foo2() 時 this 指向 obj;接著在 setTimeout 裡定義了一個匿名箭頭函式,它的 this 就是定義位置作用域的 this,也就是 foo2 中的 this,即 obj。
一句話記法:箭頭函式的 this 只跟定義它的作用域有關,與在哪裡、如何呼叫無關,而且不可被改變。
函式也是物件,因此也有方法。這三個都能改寫 this:
call: fun.call(thisArg[, arg1[, arg2[, ...]]]),立即執行,後續參數逐一傳入。
apply: fun.apply(thisArg[, [arg1, arg2, ...]]),立即執行,第二個參數是陣列。
bind: var foo = fun.bind(thisArg[, arg1[, ...]]),不執行,回傳一個已綁定上下文的新函式。
為普通函式指定:
var obj = { name: 'qiutc' }; function foo() { console.log(this); } foo.call(obj); // Object {name: "qiutc"}
為物件方法指定:
var obj = { name: 'qiutc', foo: function () { console.log(this); } } var obj2 = { name: 'tcqiu222222' }; obj.foo.call(obj2); // Object {name: "tcqiu222222"}
為建構函式指定——這裡會踩到雷:
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var p = new Person.call(obj, 'qiutc'); // Uncaught TypeError: Person.call is not a constructor(…)
因為我們 new 的是 Person.call,而它並不是建構函式。改用 bind 試試:
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var Person2 = Person.bind(obj); var p = new Person2('qiutc'); // Person {name: "qiutc"} console.log(obj); // Object {name: "qiutc2222222"}
印出來的是 Person 的實例,obj 完全沒被改到。所以:用 bind 給建構函式指定的 this,在 new 的時候不會生效。不過 bind 的參數仍然有用:
function Person(name) { this.name = name; console.log(this); } var obj = { name: 'qiutc2222222' }; var Person2 = Person.bind(obj, 'qiutc111111'); var p = new Person2('qiutc'); // Person {name: "qiutc111111"}
var afoo = (a) => { console.log(a); console.log(this); } afoo(1); // 1 // Window var obj = { name: 'qiutc' }; afoo.call(obj, 2); // 2 // Window
call 完全改不動它。結論:箭頭函式的 this 在定義時就已決定,call、apply、bind 都無效。
只要記住「箭頭函式大法好,this 永遠不變」,實務上八成以上的 this 困擾都能避開。