來自物件導向語言背景的人,第一次接觸 JavaScript 的 this 幾乎都會被電到。在 Java 中,this 就是「當前物件」,編譯期即可確定。但在 JavaScript 中,this 是執行期動態綁定的——它的值取決於函式「怎麼被呼叫」,而不是「在哪裡定義」。
public class Test { public static void main(String[] args) { Person p = new Person("zmt",30); System.out.println(p.name); } } class Person{ String name; int age; Person(String name,int age){ this.name = name; this.age = age; } }
這裡的 this 無庸置疑地代表 p 物件,因為 Java 的方法必然屬於某個類別的某個實例,編譯時就綁定完畢。
JavaScript 的 this 可以是全域物件、當前物件或任意物件,完全取決於呼叫方式。函式呼叫大致分四種:作為普通函式、作為物件方法、作為建構函式、以及透過 apply/call 明確指定。
function test(){ alert(this); } test();
在非嚴格模式下,this 指向 window(會弹出全域物件)。在嚴格模式下則是 undefined——這是兩者最直觀的差異之一。
這是與 Java 最相近的情況:this 指向「呼叫它的那個物件」,也就是點前面的東西。
var obj = { name: '小明', show: function(){ console.log(this.name); } }; obj.show(); // "小明" var fn = obj.show; fn(); // undefined(或空字串),因為 this 變成 window
最後這兩行是經典陷阱:把方法「拆下來」單獨呼叫,this 就不再指向 obj。這也是為什麼在 React 等框架中,傳遞方法為回呼時常需要 bind。
function Person(name,age){ this.name = name; this.age = age; }
用 new Person(...) 呼叫時,this 指向新建立的物件,這時的行為就和 Java 一樣了。若漏寫 new,非嚴格模式下 this 會指向 window,導致全域變數被汙染。
function greet(greeting){ return greeting + ',我是' + this.name; } greet.call({ name: '小明' }, '你好'); // "你好,我是小明"
call 與 apply 會在呼叫的當下指定 this,bind 則回傳一個 this 已固定的新函式。箭頭函式是另一個特例:它沒有自己的 this,會沿用定義所在外層作用域的 this,且無法被 call/apply 改寫。
JavaScript 的 this 不是「我這個物件」,而是「這次呼叫的持有者」。判斷方法很簡單:看函式是怎麼被呼叫的。寫在點後面就是那個物件,獨立呼叫就是全域(或嚴格模式下的 undefined),用 new 就是新實例,用 call/apply/bind 就是指定值。