javascript 中 this 工作原理
问题: JavaScript 中的 this 关键字是如何工作的?
回答:
this 关键字在 JavaScript 中扮演着关键角色,它表示当前正在执行代码的上下文对象。其值取决于函数的调用方式和执行环境。
函数调用方式:
- 普通函数调用: this 指向全局对象(在浏览器中为 window,在 Node.js 中为 global)。
- 对象方法调用: this 指向调用方法的对象。
- 回调函数调用: this 的值会变,取决于回调函数的调用方式。
箭头函数:
箭头函数没有自己的 this,而是继承调用它的函数的 this。
执行环境:
- 严格模式: this 总指向 undefined。
- 非严格模式:如果找不到 this 的有效值,则指向全局对象。
使用示例:
普通函数:
function greet() {
console.log(this); // window
}
greet();
对象方法:
const person = {
name: "John",
greet() {
console.log(this.name); // John
}
};
person.greet();
回调函数:
const button = document.getElementById("btn");
button.addEventListener("click", function() {
console.log(this); // DOM 元素
});
箭头函数:
const obj = {
name: "Jane",
greet() {
const arrowGreet = () => {
console.log(this.name); // Jane
};
arrowGreet();
}
};
obj.greet();