//1. 全局作用域中的 this
// 在全局作用域中(任何函数外部),this 指向全局对象
console.log(this === window); // true(浏览器环境)
// 定义全局变量
var globalVar = 'Hello';
console.log(this.globalVar); // 'Hello'
// 2. 函数内部的 this
// 在非箭头函数中,this 的指向取决于函数的调用方式:
// 2.1 普通函数调用
// this 指向全局对象(严格模式下为 undefined)。
function showThis() {
console.log(this);
}
showThis(); // 在浏览器中输出: Window {...}
// 2.2 作为对象方法调用
// this 指向调用该方法的对象。
const person = {
name: 'Alice',
greet() {
console.log(`Hello, ${this.name}!`);
}
};
person.greet(); // 输出: "Hello, Alice!"
// 2.3 作为构造函数调用
// this 指向新创建的实例对象。
function Car(model) {
this.model = model;
}
const myCar = new Car('Tesla');
console.log(myCar.model); // 输出: "Tesla"
// 3. 箭头函数中的 this
// 箭头函数不绑定自己的 this,而是继承自定义时的上下文。
const obj = {
name: 'Alice',
regularFunc() {
console.log(this.name); // 继承自 obj
},
arrowFunc: () => {
console.log(this.name); // 继承自全局作用域(非严格模式下为 undefined)
}
};
obj.regularFunc(); // 输出: "Alice"
obj.arrowFunc(); // 输出: undefined(浏览器环境中)