JavaScript 中的 This 指向非常重要,稍有不懂便看不懂誰調用誰,輸出的是從哪裏來;所以我在這裏總結幾個常見的指向性問題:
- 全局作用域或者普通函數中 this 指向全局對象 window。
- 方法調用中誰調用 this 指向誰。
- 在構造函數或者構造函數原型對象中 this 指向構造函數的實例。
- 箭頭函數中指向外層作用域的 this
1. 全局作用域或者普通函數中 this 指向全局對象 window。
//直接打印
console.log(this) //window
//function聲明函數
function bar () {console.log(this)}
bar() //window
//function聲明函數賦給變量
var bar = function () {console.log(this)}
bar() //window
//自執行函數
(function () {console.log(this)})(); //window
2. 方法調用中誰調用 this 指向誰
//對象方法調用
var person = {
run: function () {console.log(this)}
}
person.run() // person
//事件綁定
var btn = document.querySelector("button")
btn.onclick = function () {
console.log(this) // btn
}
//事件監聽
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調用自己,所以this指向obj
3. 在構造函數或者構造函數原型對象中 this 指向構造函數的實例
//不使用new指向window
function 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
4. 箭頭函數中指向外層作用域的 this
var obj = {
foo() {
console.log(this);
},
bar: () => {
console.log(this);
}
}
obj.foo() // {foo: ƒ, bar: ƒ}
obj.bar() // window