JavaScript中This指向問題

1 全局作用域或者普通函數(shù)的this指向Windows

//直接打印

console.log(this) //window

//function聲明函數(shù)

function bar(){ console.log( this ) }

bar() //window

//function聲明函數(shù)賦給變量

var bar = function(){console.log(this)}

bar() //window

//自執(zhí)行函數(shù)

(function(){console.log(this)})(); //window

2 方法調(diào)用中誰調(diào)用this指向誰

//對象方法調(diào)用

var person = {

? ? run: function(){console.log(this)}

}

person.run() // person

//事件綁定

var btn = document.querySelector("button")

btn.onclick = function(){

? ? console.log(this) // btn

}

//事件監(jiān)聽

var btn = document.querySelector("button")

btn.addEventListener('click', function(){

? console.log(this) //btn

})

//jquery的ajax

$.ajax({

? ? self: this,

? ? type:"get",

? ? url: url,

? ? async:true,

? ? success: function(res){

? ? ? ? console.log(this) // this指向傳入$.ajxa()中的對象

? ? ? ? console.log(self) // window

? ? }

? });

//這里說明一下,將代碼簡寫為$.ajax(obj) ,this指向obj,在obj中this指向window,因為在在success方法中,獨享obj調(diào)用自己,所以this指向obj

3 在構(gòu)造函數(shù)或者構(gòu)造函數(shù)原型對象中,this指向構(gòu)造函數(shù)的實例

//不使用new指向windowfunction

Person (name) {

? ? console.log(this) // window? ?

????this.name = name;

}

Person('inwe')

//使用new

function Person (name) {

? ? ? this.name = name

? ? ? console.log(this) //people

? ? ? self = this?

}

? var people = new Person('iwen')

? console.log(self === people) //true

//這里new改變了this指向,將this由window指向Person的實例對象people

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容