JavaScript中this指向取决于函数被调用时的执行上下文:普通调用(非严格模式→全局对象,严格模式→undefined)、对象方法调用(→点号左侧对象)、显式绑定(call/apply/bind→指定对象)、new调用(→新实例)、箭头函数(→继承外层this),优先级为new>显式>隐式>默认。
JavaScript 中的 this 指向谁,不取决于函数定义的位置,而取决于函数**被调用时的执行上下文**。换句话说,看的是“谁在调用这个函数”,而不是“这个函数写在哪”。掌握 this 的核心规律,关键在于识别调用方式。
当函数独立调用(没有点号、没有 new、没有 call/apply/bind)时,this 的值由是否启用严格模式决定:
window,Node.js 中是 global)undefined,不会自动绑定到全局对象例如:
function foo() { console.log(this); }
foo(); // 非严格模式 → window;严格模式 → undefined
当函数作为对象的属性被调用(即用 obj.method() 形式),this 指向该对象(即点号左边的对象)。
例如:
const obj = {
name: 'Alice',
say() { console.log(this.name); }
};
obj.say(); // 'Alice' → this 指向 obj
const fn = obj.say;
fn(); // undefined(严格模式)或 window.name → this 不再是 obj
通过 call、apply 或 bind 调用函数时,this 被明确指定为第一个参数的值。
func.call(obj, a, b) → this = objfunc.apply(obj, [a, b]) → this = objconst bound = func.bind(obj) → 返回的新函数永远以 obj 为 thisbind 生成的函数即使再次用 call 改写,也无法覆盖原始绑定(硬绑定优先级高)使用 new 调用函数时,会创建一个新对象,并将 this 绑定到该新实例上。
例如:
function Person(name) {
this.name = name; // this 指向 new 出来的实例
}
const p = new Person('Bob');
console.log(p.name); // 'Bob'
箭头函数**不绑定自己的 this**,它会沿作用
域链向上查找,继承外层普通函数(或全局)的 this 值。
例如:
const obj = {
name: 'Charlie',
regular() {
console.log(this.name); // 'Charlie'
const arrow = () => console.log(this.name); // 也输出 'Charlie'
arrow();
}
};
obj.regular();
当多种绑定方式共存,按以下优先级判断 this:
不复杂但容易忽略。