this的值取决于函数调用方式而非定义位置;在对象方法或类实例方法中调用时,this指向该对象或实例,并可通过===或instanceof验证,而箭头函数因不绑定this会干扰验证。

直接打印 this 的值本身不能自动“证明”它指向当前调用的对象实例,因为 this 的绑定取决于函数的**调用方式**,而非定义位置。但通过精心设计的调用场景并结合输出对比,可以清晰验证其指向。
在对象方法中打印 this
当函数作为对象的方法被调用时,this 指向该对象。
const obj = {
name: 'Alice',
sayName() {
console.log(this); // 输出:{ name: 'Alice', sayName: [Function: sayName] }
console.log(this === obj); // true
}
};
obj.sayName();
这里 this 打印出整个对象,且与 obj 严格相等,直观表明它指向当前调用该方法的对象实例。
对比不同调用方式下的 this 值
同一函数,调用方式不同,this 不同——这是验证的关键。
- 作为方法调用:
obj.fn()→this是obj - 单独调用:
const f = obj.fn; f();→ 非严格模式下this是window(或globalThis),严格模式下是undefined - 用
call/apply/bind显式绑定 →this是指定的对象
分别打印这几种情况下的 this,并和预期对象做 === 判断,就能实证其动态绑定特性。
在类方法中打印 this(ES6 Class)
类的方法本质也是对象属性上的函数,行为一致。
class Person {
constructor(name) {
this.name = name;
}
introduce() {
console.log(this); // 输出:Person { name: 'Bob' }
console.log(this instanceof Person); // true
}
}
const p = new Person('Bob');
p.introduce();
此时 this 不仅是当前实例对象,还能通过 instanceof 进一步确认其类型和构造来源。
避免箭头函数干扰验证
箭头函数不绑定自己的 this,而是继承外层作用域的 this。若用于验证,会掩盖真实绑定逻辑。
- ❌ 错误示范:
sayName: () => console.log(this)—— 这里的this可能是模块顶层的this或undefined - ✅ 正确做法:始终使用普通函数(function 关键字或方法简写)来观察
this的实际绑定
确保测试函数不是箭头函数,才能真实反映调用时的 this 指向。










