this的指向在运行时由调用方式决定:全局环境中指向window;函数直接调用时指向window或undefined(严格模式);作为对象方法调用时指向该对象;构造函数中指向新实例;通过call/apply/bind可显式绑定;箭头函数则继承外层作用域的this。

JavaScript 中的 this 指向问题一直是开发者容易混淆的核心概念之一。它不是在函数定义时决定的,而是在函数**运行时**根据调用上下文动态确定的。理解 this 的指向,关键在于搞清楚函数是如何被调用的。
1. 全局上下文中的 this
在全局执行环境中(即不在任何函数内部),无论是否严格模式,this 都指向全局对象。
console.log(this === window); // true在 Node.js 环境中,全局对象是 global,但模块中的顶层 this 默认为 module.exports。
立即学习“Java免费学习笔记(深入)”;
2. 函数上下文中的 this
函数中的 this 取决于函数的调用方式,有以下几种常见情况:
3. 箭头函数中的 this
箭头函数没有自己的 this,它的 this 继承自外层作用域(词法作用域)。
const obj = { name: 'Diana', greet: () => { console.log(this.name); // this 指向外层,通常是 window 或 undefined }, delayGreet() { setTimeout(() => { console.log('Hi, ' + this.name); // this 指向 obj }, 1000); } }; obj.greet(); // 输出空或 undefined obj.delayGreet(); // 1秒后输出 'Hi, Diana'4. 事件监听中的 this
DOM 事件处理函数中的 this 通常指向绑定事件的 DOM 元素。
button.addEventListener('click', function() { console.log(this === button); // true });如果使用箭头函数,则 this 不再指向元素,而是继承外层上下文。
基本上就这些。掌握 this 的核心是记住:它由调用方式决定,而不是定义位置。多练习不同调用场景,就能逐渐形成直觉。











