JavaScript 中 this 的詳解

來源:互聯網
上載者:User

標籤:undefined   瀏覽器   function   window   實際應用   

    

this 的指向

this 是 js 中定義的關鍵字,它自動定義於每一個函數域內,但是它的指向卻讓人很迷惑。在實際應用中,this 的指向大致可以分為以下四種情況。

原文林鑫,作者部落格:https://github.com/lin-xin/blog

1.作為普通函數調用

當函數作為一個普通函數被調用,this 指向全域對象。在瀏覽器裡,全域對象就是 window。

window.name = ‘linxin‘;function getName(){    console.log(this.name);}getName();                   // linxin

可以看出,此時 this 指向了全域對象 window。
在ECMAScript5的strict 模式下,這種情況 this 已經被規定不會指向全域對象了,而是 undefined。

‘use strict‘;function fun(){    console.log(this);}fun();                      // undefined
2.作為對象的方法調用

當函數作為一個對象裡的方法被調用,this 指向該對象

var obj = {    name : ‘linxin‘,    getName : function(){        console.log(this.name);    }}obj.getName();              // linxin

如果把對象的方法賦值給一個變數,再調用這個變數:

var obj = {    fun1 : function(){        console.log(this);    }}var fun2 = obj.fun1;fun2();                     // window

此時調用 fun2 方法 輸出了 window 對象,說明此時 this 指向了全域對象。給 fun2 賦值,其實是相當於:

var fun2 = function(){    console.log(this);}

可以看出,此時的 this 已經跟 obj 沒有任何關係了。這時 fun2 是作為普通函數調用。

3.作為建構函式調用

js中沒有類,但是可以從構造器中建立對象,並提供了 new 運算子來進行調用該構造器。構造器的外表跟普通函數一樣,大部分的函數都可以當做構造器使用。當建構函式被調用時,this 指向了該建構函式執行個體化出來的對象。

var Person = function(){    this.name = ‘linxin‘;}var obj = new Person();console.log(obj.name);      // linxin

如果建構函式顯式的返回一個對象,那麼 this 則會指向該對象。

var Person = function(){    this.name = ‘linxin‘;    return {        name : ‘linshuai‘    }}var obj = new Person();console.log(obj.name);      // linshuai

如果該函數不用 new 調用,當作普通函數執行,那麼 this 依然指向全域對象。

4.call() 或 apply() 調用

通過調用函數的 call() 或 apply() 方法可動態改變 this 的指向。

var obj1 = {    name : ‘linxin‘,    getName : function(){        console.log(this.name);    }}var obj2 = {    name : ‘linshuai‘}obj1.getName();             // linxinobj1.getName.call(obj2);    // linshuaiobj1.getName.apply(obj2);   // linshuai


JavaScript 中 this 的詳解

聯繫我們

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