JavaScript中this指向問題

this的指向在函數定義的時候是確定不了的,只有函數執行的時候才能確定,this最終指向調用它的對象。
1.通過函數名直接調用,this指向window

function func(){
console.log(this)
}
test() // this -> window

2.函數作爲window內置函數的回調函數調用,this指向window

setTimeout(function func(){
console.log(this)
},100)
// this -> window

3.通過對象調用函數,this指向這個對象

var obj = {
    func: function(){
    console.log(this)
}
  
}
obj.func() // this -> obj

4.函數作爲構造函數,this指向新new出的對象

function func(){
console.log(this)  // this -> window
}
var newfunc = new func() // this -> newfunc

5…利用apply、call改變this指向

var obj = {}
function func(){
console.log(this)
}
func() // this -> window
func.call(obj) // this -> obj
func.apply(obj) // this -> obj

當使用apply和call上下文調用的時候this指向傳入的第一個參數

友情鏈接:點擊查看 JavaScript作用域、閉包、this指向系列文章目錄

友情鏈接:點擊查看所有文章目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章