返回
JavaScript 中的 this 的工作原理
前端
2023-11-12 00:42:56
this 的工作原理
JavaScript 有一套完全不同于其它语言的对 this 的处理机制。在五种不同的情况下,this 指向的各不相同。
全局范围内
当在全部范围内使用 this,它将会指向 window 对象。
console.log(this); // 输出: Window
对象方法中
当在对象的方法中使用 this,它将会指向该对象本身。
const person = {
name: 'John',
age: 30,
greet: function() {
console.log(this.name); // 输出: John
}
};
person.greet();
构造函数中
当在构造函数中使用 this,它将会指向新创建的对象。
function Person(name, age) {
this.name = name;
this.age = age;
}
const john = new Person('John', 30);
console.log(john.name); // 输出: John
console.log(john.age); // 输出: 30
类中
当在类中使用 this,它将会指向类的实例。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(this.name); // 输出: John
}
}
const john = new Person('John', 30);
john.greet();
箭头函数中
当在箭头函数中使用 this,它将会指向其父作用域中的 this。
const person = {
name: 'John',
age: 30,
greet: () => {
console.log(this.name); // 输出: undefined
}
};
person.greet();
绑定函数中
当在绑定函数中使用 this,它将会指向绑定的对象。
const person = {
name: 'John',
age: 30,
greet: function() {
console.log(this.name); // 输出: John
}
};
const boundGreet = person.greet.bind({ name: 'Jane' });
boundGreet(); // 输出: Jane
总结
JavaScript 中的 this 指向当前执行代码的对象。在不同的上下文中,this 的值也不同。在全局上下文中,this 指向 window 对象。在对象方法中,this 指向该对象本身。在构造函数中,this 指向新创建的对象。在类中,this 指向类的实例。在箭头函数中,this 指向其父作用域中的 this。在绑定函数中,this 指向绑定的对象。