javascript中的this用法

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

總結:java

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

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

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

一:純粹的函數調用spa

這是函數的最經常使用法,屬於全局性調用,這裏this就表明全局對象windowcode

 

    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.blog

 

 

二:做爲對象方法的調用ip

函數還能夠做爲某個對象的方法調用,這時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    
相關文章
相關標籤/搜索