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