請看下面的代碼,最後alert出來的是什麼呢?
var name = "Bob"; var nameObj ={ name : "Tom", showName : function(){ alert(this.name); }, waitShowName : function(){ setTimeout(this.showName, 1000); } }; nameObj.waitShowName();
要解決這個問題我們需要瞭解Javascript的this關鍵字的用法。
this指向哪裡?
一般而言,在Javascript中,this指向函數執行時的當前對象。
In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked.
——jQuery Fundamentals (Chapter 2), by Rebecca Murphey
值得注意,該關鍵字在Javascript中和執行環境,而非聲明環境有關。
The this keyword is relative to the execution context, not the declaration context.
我們舉個例子來說明這個問題:
var someone = { name: "Bob", showName: function(){ alert(this.name); }}; var other = { name: "Tom", showName: someone.showName} other.showName(); //Tom
this關鍵字雖然是在someone.showName中聲明的,但啟動並執行時候是other.showName,所以 this指向other.showName函數的當前對象,即other,故最後alert出來的是other.name。