JavaScript中this指向取决于函数调用方式而非定义方式:obj.method()时this指向obj;独立调用func()时非严格模式下指向全局对象、严格模式下为undefined;call/apply/bind可显式绑定this;箭头函数无this,继承外层普通函数的this。

JavaScript 中方法调用时 this 指向哪个对象,取决于**函数是如何被调用的**,而不是如何定义的。核心原则是:谁调用,this 就指向谁(严格模式下有例外,但方法调用场景中基本遵循该直觉)。
普通方法调用(obj.method())
当一个函数作为对象的属性被调用时,this 指向该对象。
- const obj = { name: 'Alice', greet() { console.log(this.name); } }; obj.greet(); // 'Alice' → this 指向 obj
- 即使函数先赋值给变量再调用,只要调用形式不是“点号+括号”,this 就会丢失(变成全局或 undefined)
独立函数调用(func())
如果函数不通过对象调用,而是直接执行(即没有点号前缀),this 指向:
- 非严格模式下:全局对象(浏览器中是 window,Node.js 中是 global)
- 严格模式下:undefined
- function foo() { console.log(this); } foo(); // 非严格下是 window,严格下是 undefined
使用 call / apply / bind 显式绑定
这些方法可强制指定 this 的值:
立即学习“Java免费学习笔记(深入)”;
- func.call(obj, arg1, arg2):立即执行,this 绑定为 obj
- func.apply(obj, [arg1, arg2]):同上,参数以数组传入
- const bound = func.bind(obj):返回新函数,永久绑定 this 为 obj
箭头函数没有自己的 this
箭头函数不绑定 this,它会沿作用域链向上查找外层普通函数的 this 值(词法绑定):
- const obj = { name: 'Bob', regular() { return () => console.log(this.name); } }; const fn = obj.regular(); fn(); // 'Bob' —— this 继承自 regular 方法的 this
- 因此箭头函数不能用 call/apply/bind 改变 this


















