詳解Javascript中的this關鍵字

來源:互聯網
上載者:User

請看下面的代碼,最後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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.