JavaScript基礎概念之----this關鍵字

建立函數時,系統會(在後臺)建立一個名爲 this 的關鍵字,它連接到運行該函數的對象。函數

var person = {
    name:'adhehe',
    age:23,
    getName:function(){
     // return person.name
return this.name } } //person.getName() 輸出adhehe

this 值會被傳遞給全部函數,其值基於在運行時調用函數的上下文。this

var a = 1;
var o = { a:2 }
var func = function(){
    return this['a']
}

o.func = func;

o.func() //輸出2
func() //輸出1

在嵌套函數中使用this關鍵字,引用head對象(即window)spa

var o = {
    func1:function(){
        console.log(this) //輸出o
        
        var func2 = function(){
            console.log(this) //輸出window,今後處開始this都是window對象

            var func3 = function(){
                console.log(this) //輸出window
            }()
        }()
    }
}

o.func1()

當匿名函數在函數內部調用時,匿名函數內的this值將是對head對象的引用(即window)prototype

var o = {
    func1:function(func){
        func(); //輸出window
        console.log(this) //輸出o
    }
}

o.func1(function(){
    console.log(this)
})

能夠簡單地在父函數中使用做用域鏈來保留對 this 的引用。code

var o = {
    func1:function(){
        var that = this;
        console.log(this) //輸出o
        
        var func2 = function(){
            console.log(that) //輸出o

            var func3 = function(){
                console.log(that) //輸出o
            }()
        }()
    }
}

o.func1()

使用 new 關鍵字調用函數時,this 值引用實例自己。對象

原型方法內的this關鍵字引用構造函數實例,即在prototype對象中的方法內部使用this關鍵字時,this可用於引用實例。若是該實例不包含所要查找的屬性,則繼續在原型上查找。blog

相關文章
相關標籤/搜索