千鋒教育JavaScript全套視頻教程(10天學(xué)會Js,前端javascrip

P118 this指向
JavaScript中的this關(guān)鍵字是一個非常重要的概念,它在不同的情況下指向不同的對象。
this關(guān)鍵字的指向可以根據(jù)函數(shù)的調(diào)用方式而變化。
在全局作用域下,this指向window
在私有作用域下有以下幾種情況
1.普通函數(shù):this指向window
function myFunction() {
?console.log(this); // 輸出 window
}
myFunction();
2.定時器中的函數(shù):this指向window
function fun() { console.log(this);???}
setTimeout(fun,1000) // 輸出 window
3.對象中的函數(shù):this指向前面的對象
const myObj = {
name: 'John',
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
myObj.greet(); // 輸出 "Hello, my name is John"
4.事件處理函數(shù):this指向事件源
btn.onclick =function() {
??????console.log(this);???//指向btn
}
5.自執(zhí)行函數(shù):this指向window
?function fun() {console.log(this);???// 輸出 window}
(fun)()
6.構(gòu)造函數(shù):this指向?qū)嵗?/p>
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // 輸出 "John"
7.原型對象:this指向?qū)嵗?/p>
8.箭頭函數(shù):this指向定義函數(shù)時的上下文
const myObj = {
name: 'John',
greet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
myObj.greet(); // 輸出 "Hello, my name is undefined"