返回
JS 的 this 指向:掌握四项规则,秒懂指向奥秘
前端
2023-09-03 11:16:47
欢迎来到 JavaScript 的 fascinating 世界,我们将踏上理解 this 指向的神秘旅程。抛开对其他语言中 this 的固有认知,让我们从一个全新的视角去探索。遵循四项黄金规则,我们将拨开 this 指向的神秘面纱,让它变得清晰易懂。
规则 1:函数调用
当一个函数独立调用时,this 指向该函数所在的对象(global object)。例如:
function hello() {
console.log(this); // 输出全局对象
}
规则 2:方法调用
当一个函数被作为对象的方法调用时,this 指向该对象本身。例如:
const obj = {
name: 'John Doe',
greet() {
console.log(this.name); // 输出 'John Doe'
},
};
规则 3:构造函数调用
当一个函数被用作构造函数(使用 new 调用)时,this 指向新创建的对象。例如:
function Person(name) {
this.name = name;
}
const person1 = new Person('Jane Doe');
console.log(person1.name); // 输出 'Jane Doe'
规则 4:特殊情况下
在一些特殊情况下,this 的指向会受到影响:
- bind() 方法: bind() 方法可以创建一个新函数,将 this 绑定到一个特定的对象。例如:
const obj = {
name: 'John Doe',
};
const boundGreet = obj.greet.bind(obj);
boundGreet(); // 输出 'John Doe'
- 箭头函数: 箭头函数的 this 指向其所在的作用域中的 this。例如:
const obj = {
name: 'John Doe',
greet: () => {
console.log(this); // 输出全局对象
},
};
应用
掌握了这些规则,我们就可以灵活地使用 this 指向,为 JavaScript 程序赋予强大的灵活性。例如:
- 事件处理程序: 在事件处理程序中,this 指向触发事件的元素。例如:
const button = document.getElementById('button');
button.addEventListener('click', function() {
console.log(this); // 输出按钮元素
});
- 自定义对象: 自定义对象的方法可以利用 this 指向访问对象的内部状态。例如:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const person1 = new Person('John Doe');
person1.greet(); // 输出 'Hello, my name is John Doe.'