千锋教育JavaScript全套视频教程(10天学会Js,前端javascrip

P118 this指向
JavaScript中的this关键字是一个非常重要的概念,它在不同的情况下指向不同的对象。
this关键字的指向可以根据函数的调用方式而变化。
在全局作用域下,this指向window
在私有作用域下有以下几种情况
1.普通函数:this指向window
function myFunction() {
console.log(this); // 输出 window
}
myFunction();
2.定时器中的函数:this指向window
function fun() { console.log(this); }
setTimeout(fun,1000) // 输出 window
3.对象中的函数:this指向前面的对象
const myObj = {
name: 'John',
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
myObj.greet(); // 输出 "Hello, my name is John"
4.事件处理函数:this指向事件源
btn.onclick =function() {
console.log(this); //指向btn
}
5.自执行函数:this指向window
function fun() {console.log(this); // 输出 window}
(fun)()
6.构造函数:this指向实例
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // 输出 "John"
7.原型对象:this指向实例
8.箭头函数:this指向定义函数时的上下文
const myObj = {
name: 'John',
greet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
myObj.greet(); // 输出 "Hello, my name is undefined"