this的值由函数调用时的上下文决定:普通调用时非严格模式指向全局对象、严格模式为undefined;箭头函数继承外层调用时的this;对象方法调用时指向点号前的对象;call/apply/bind可显式绑定;new调用时指向新实例。
this 的值不是由函数定义时决定的,而是由函数**调用时的上下文**决定的。它不继承外层作用域,也不受 function 声明位置影响——只看「谁在调用它」和「怎么调用的」。
这是最容易踩坑的场景:函数独立执行,没绑定任何对象。
this 指向 window(浏览器)或 global(Node.js)this 是 undefined,访问 this.xxx 会报 TypeError
this,它沿用外层函数作用域的 this 值(注意:不是词法作用域的「变量」,而是调用时外层函数的 this)function foo() {
console.log(this);
}
foo(); // 非严格模式 → window;严格模式 → undefined
const obj = {
name: 'test',
bar: () => console.log(this) // 箭头函数,this 取外层(全局)上下文
};
obj.bar(); // 仍是 window 或 undefined(取决于外层是否严格模式)
关键看「点号左边是谁」:即 obj.method() 中的 obj。

method() {})和传统写法(method: function() {})行为一致const user = {
name: 'Alice',
getName() {
return this.name;
}
};
user.getName(); // 'Alice' → this 指向 user
const fn = user.getName;
fn(); // undefined(非严格)或 TypeError(严格)→ this 不再是 user
这三个 API 都允许你「强行指定」this 值,优先级高于隐式绑定。
func.call(obj, arg1, arg2):立即执行,this 绑定为 obj
func.apply(obj, [arg1, arg2]):同上,参数传数组func.bind(obj):返回新函数,this 永久绑定为 obj(不可被后续 call/apply 覆盖)null 或 undefined,非严格模式下仍自动转为全局对象;严格模式下就是 null/undefined
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
const person = { name: 'Bob' };
greet.call(person, 'Hi'); // 'Hi, Bob'
greet.bind(person)('Hello'); // 'Hello, Bob'
当函数用 new 调用时,引擎会自动创建空对象、将其设为 this、执行函数体、最后返回该对象(除非显式返回其他对象)。
function 声明(class 构造器本质也是函数)new,会报 TypeError: xxx is not a constructor
function Person(name) {
this.name = name; // this 指向新实例
}
const p = new Person('Charlie');
console.log(p.name); // 'Charlie'
// 错误示例:箭头函数无法作为构造器
const BadPerson = (name) => { this.name = name };
new BadPerson('Dave'); // TypeError
真正难的不是记住规则,而是识别「调用形式」:是 obj.fn()?还是 fn()?有没有 call?有没有 new?有没有箭头函数嵌套?每次不确定时,就回看调用那一行代码的完整写法。