javascript中的this用法

來源:互聯網
上載者:User

標籤:nbsp   rip   情況   name   方法調用   div   blog   函數對象   var   

this這個關鍵字在javascript中很常見,也很重要。那麼this到底是指什麼呢?

總結:

1.this代表函數運行時自動產生的一個內部對象,只能在函數內部使用;

2.this始終指向調用函數的那個對象;

下面分四種情況,詳細討論this的用法

一:純粹的函數調用

這是函數的最常用法,屬於全域性調用,這裡this就代表全域對象window

 

    function test(){        this.x = 1;        alert(this.x);        console.log(this);//Window     }    test();

 

而下邊這個案例:

        var x = 2;        function test(){            this.x = 1;            alert(this.x);            console.log(this);//Window         }        test();        console.log(x);//1    

就可以證明這裡函數中的this指的是window.

 

 

二:作為對象方法的調用

函數還可以作為某個對象的方法調用,這時this就指這個上級對象.

        function test(){            console.log(this.x);//1            console.log(this);//o        }        var o = {};        o.x = 1;        o.m = test;        o.m();    

三:作為建構函式調用

所謂建構函式,就是通過這個函數產生一個新的對象。這時,this就指向這個新對象

        function Test(name){            this.name = name;            console.log(this);//Test {name: "hehe"}        }        var t = new Test("hehe");    

四:apply調用

apply()是函數對象的一個方法,它的作用是改變函數的調用對象,它的第一個參數就是改變後的調用這個函數的對象。

this這裡值得就是第一個參數的值,若參數為空白,則預設值為全域對象

        var x = 0;        function test () {            console.log(this);            console.log(this.x);        }        var o = {};        o.x = 2;        o.m = test;        o.m();//this.x-->2        o.m.apply();//this.x-->0        // 結果:        // Object {x: 2}        // 2        // Window {…}        // 0    

 

 

  

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.