理解JavaScript中的this

來源:互聯網
上載者:User

一、this出現的幾種情況
1、建構函式中的this
 function Fn(){
    console.log(this);  
}
var obj1 = new Fn(); //obj1, 函數Fn中的this指向執行個體對象obj1
2、普通函數中的this
 function Fn1(){
    console.log(this);  
}
Fn1(); //window, Fn1屬於window全域對象的一個屬性,即:Fn1()===window.Fn1(),函數Fn1中的this指向window對象
Fn()===window.Fn(); //window, Fn屬於window全域對象的一個屬性,即:Fn()===window.Fn(),函數Fn中的this指向window對象
3、對象中的this
 var obj = {
    that: this,
    fn: function(){
        console.log(this);  
    }
}
console.log(obj.that); //window, this不存在Object對象中的,this指向window全域對象
obj.fn(); //obj, this指向調用其所在函數的對象
二、總結:
1、this不存在Object對象中的,它只存在一個Function類型的函數中
2、this指向使用new操作符執行個體化其所在函數的執行個體對象
3、this還指向調用其所在函數的對象
三、誤區:
1、注意在全域函數中的this
 var obj = {
    fn: function(){
        function test(){
            console.log(this);
        }
        test();
    }
}
obj.fn(); //window, test屬於window對象的屬性,因此this指向的是window對象,而不是obj對象
2、上面的例子中,this一般被誤認為obj對象,其實不是的,它指向window全域對象,但可以通過obj中的一個局部變數來指向obj
 var obj = {
    fn: function(){
        var self = this;
        function test(){
            console.log(self); //用self來指向obj對象
        }
        test();
    }
}
obj.fn(); //obj
3、方法的賦值運算式 
 var obj = {
    fn: function(){
        var self = this;
        function test(){
            console.log(self); //用self來指向obj對象
        }
        test();
    }
}
var fn = obj.fn;
fn(); //window, 上一句中變數fn是window對象的一個屬性,此時的self變數儲存的還是window對象
綜上:this總是指向其所在函數類型的對象以及調用其所在函數中的(頂層)對象.



摘自 華子yjh

聯繫我們

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