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的指向,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526013.html
標籤:JavaScript
