JavaScript 中的 this 指向当前执行上下文中的对象,由函数调用方式决定:普通调用时非严格模式指向全局对象、严格模式为 undefined;对象方法调用时指向点号左侧对象;call/apply/bind 可显式绑定;箭头函数继承外层普通函数的 this;new 调用时指向新创建的实例对象。

JavaScript 中的 this 指向**当前执行上下文中的对象**,但它不是由函数定义时决定的,而是由**函数如何被调用**决定的。理解 this 的关键,是看函数调用时的“调用位置”和“调用方式”,而不是函数写在哪、怎么声明的。
普通函数调用(非严格模式 vs 严格模式)
当函数独立调用(没有点号、没有 new、没有 call/apply/bind),this 的值取决于是否启用严格模式:
例如:
function foo() { console.log(this); }foo(); // 非严格模式 → window;严格模式 → undefined
对象方法调用(隐式绑定)
当函数作为对象的属性被调用(即通过 obj.method() 形式),this 指向该对象(即点号左边的对象)。
立即学习“Java免费学习笔记(深入)”;
注意:只看调用时的“最近点号”,不看函数定义位置或赋值过程:
const obj = { name: 'Alice', say: function() { console.log(this.name); } };obj.say(); // 'Alice' —— this 指向 obj
const bar = obj.say;
bar(); // undefined(非严格)或报错(严格)—— 此时已脱离 obj,变成普通调用
显式绑定与硬绑定(call / apply / bind)
使用 call、apply 或 bind 可以**手动指定 this 值**:
-
func.call(obj, arg1, arg2):立即执行,this 绑定为obj -
func.apply(obj, [arg1, arg2]):同上,参数以数组传入 -
const bound = func.bind(obj):返回新函数,this 永远绑定为obj(硬绑定,无法被后续 call 覆盖)
bind 返回的函数即使再用 call 传入其他对象,this 仍保持原始绑定值(除非是箭头函数或 new 调用等特殊情况)。
箭头函数与 new 调用
箭头函数没有自己的 this,它会**沿作用域链向上查找外层普通函数的 this 值**(词法绑定),且不能用 call/apply/bind 修改。
而用 new 调用函数时,this 指向**新创建的实例对象**,此时 this 由 new 机制决定,优先级高于隐式或显式绑定。
例如:
function Person(name) {this.name = name;
this.getName = () => this.name; // 箭头函数继承构造函数的 this
}
const p = new Person('Bob');
p.getName(); // 'Bob'










