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指向的方法
函數是對象,有屬于自己的屬性和方法。