JS中的this指向問題
this的指向問題
全局作用域
在JS中,全局的變量和函數附著在global對象上,全局對象在瀏覽器環境下是window對象。
- 在全局作用域中,
this指向全局對象window。
console.log(this); // window對象
console.log(window); // window對象
console.log(this === window); // true
var a = 3;
console.log(a); // 3
console.log(window.a); // 3
console.log(this.a); // 3
console.log(a === window.a && window.a === this.a); // true
function say(){
console.log("hi");
}
this.say(); // hi
全局變量和window對象的關系
-
使用
var聲明定義的全局變量會被掛載到全局對象window上。 -
使用
let、const聲明定義的全局變量不會被掛載到全局對象window上。
普通函數
普通函數內部的this指向調用這個函數的對象。
案例1
function testThis(){
console.log(this);
}
testThis(); // 輸出結果: window對象
testThis()在全局作用域中被調用,相當于執行了window.testThis();,則函數被調用時,內部的this指向window.
案例2
var obj = {
test(){
console.log(this);
}
}
obj.test(); // obj
普通函數作為對象上的方法時,
this指向調用方法的對象.
案例3
var obj = {
test1(){
console.log(this);
},
test2(){
test(); // 這里相當于執行了window.test();
}
}
function test(){
console.log(this);
}
obj.test1(); // obj
obj.test2(); // window
test(); // window
構造函數
構造函數一般是通過new關鍵字調用的,其內部的this指向新創建的對象。
function Person(name,age){
this.name = name;
this.age = age;
console.log(this);
}
const person1 = new Person('張三',20);
const person2 = new Person('李四',18);
構造函數利用指向新對象的
this,將傳入的name和age屬性直接賦值給新對象。通過最后的console.log(this)語句也可以檢測出this的指向。
綁定事件函數
const btn = document.querySelector('button');
btn.onclick = function(){
console.log(this);
}
this指向觸發該事件的對象。此處,點擊事件觸發時,
this指向按鈕這個DOM對象。
箭頭函數
箭頭函數沒有屬于自己的this。因此,箭頭函數內部使用的this就是箭頭函數所在上下文的this.
var obj = {
test1(){
console.log(this);
},
test2:()=>{
console.log(this);
}
}
obj.test1(); // obj
obj.test2(); // window
test2是箭頭函數,沒有屬于自己的this。在其內部輸出的this是obj所在上下文的this,即window。
改變this指向的方法
函數是對象,有屬于自己的屬性和方法。
函數有call和apply方法可以改變調用時this的指向。

浙公網安備 33010602011771號