Js中的this關鍵字

來源:互聯網
上載者:User

標籤:c   blog   a   http   color   com   

this關鍵字

每個方法都包含兩個內部屬性,其中一個就是this。

  js中,this引用的是函資料以執行操作的對象,也就是函數在執行時所處的範圍(通俗:就是哪個對象.出了這個函數,那麼函數裡的this就代表哪個對象)。
  但因為js的弱類型機制及函數本身就是一個Function對象執行個體的原因,使得一個函數的調用者可以在運行時由一個切換到另一個。

看看下面這個例子:
var color = "blue";  //定義一個全域變數 color,相當於 window.color= "blue"

var o = { color: "red" };  //定義一個全域變數 o,相當於 window.o={ color: "red" }
  ////定義一個全域變數(方法)sayColor,相當於window. sayColor =function(){alert(this.color); }

    function sayColor() {

       alert(this.color);

    }

sayColor(); //輸出blue.相當於window.sayColor();
//因此,此時sayColor中的this代表window.所以this.color=window.color


o.sayColor = sayColor; //此時將sayColor的函數指標賦值給o對象的屬性sayColor

o.sayColor(); //那麼此時sayColor裡的this代表的是o,所以this.color=o.color="red"

 

本文來源於http://www.cnblogs.com/jameszou/archive/2011/08/15/2138595.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.