JavaScript内部函数的this默认绑定取决于调用方式而非定义位置:独立调用时,非严格模式指向全局对象,严格模式为undefined;箭头函数无this绑定,直接继承外层词法作用域的this。

JavaScript 内部函数的 this 默认绑定,不看它写在哪,只看它怎么被调用。所谓“内部函数”,比如嵌套在另一个函数里的普通函数(非箭头函数),它的 this 依然严格遵循四条绑定规则,而默认绑定是兜底规则——当其他更高优先级的绑定(new、显式、隐式)都不适用时,才触发。
默认绑定:独立调用 → 全局或 undefined
当一个函数以最简单的方式执行:foo()(没有点号、没有 new、没用 call/apply/bind),
那就属于默认绑定。
- 非严格模式下:
this指向全局对象(浏览器中是window,Node 中是global) - 严格模式下:
this是undefined
function outer() {
function inner() {
console.log(this); // 独立调用 → 触发默认绑定
}
inner(); // 这里就是独立调用
}
outer();
// 非严格模式:window
// 严格模式:undefined注意:inner 虽然定义在 outer 里面,但它的 this 和 outer 的 this 完全无关,也不继承外层作用域的 this(那是箭头函数才有的行为)。
常见陷阱:看似“内部”,实则“独立”
很多问题出在函数被“抽出来”再调用,表面是内部函数,实际调用时已脱离上下文:
const obj = {
name: 'Alice',
method() {
function inner() {
console.log(this.name); // this 不是 obj!
}
inner(); // ✅ 独立调用 → 默认绑定
}
};
obj.method(); // 输出 undefined(严格模式)或 window.name(非严格)即使 inner 在 method 里定义,只要它是 inner() 这样直接调,this 就不会自动指向 obj。
立即学习“Java免费学习笔记(深入)”;
如何让内部函数正确拿到外层 this?
有三种常用解法:
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
-
用箭头函数(最简洁):它没有自己的
this,直接沿作用域链取外层thismethod() { const inner = () => console.log(this.name); // this === obj inner(); } -
缓存
this变量(传统写法):method() { const self = this; function inner() { console.log(self.name); // 显式使用 self } inner(); } -
显式绑定(如
inner.call(this)或inner.bind(this)):method() { function inner() { console.log(this.name); } inner.call(this); // 强制 this 指向 obj }
特别提醒:箭头函数不参与默认绑定
箭头函数根本没有 this 绑定机制,它跳过所有四条规则,直接捕获定义时所在词法作用域的 this 值。所以:
const obj = { name: 'Bob' };
function foo() {
const arrow = () => console.log(this.name);
arrow(); // this 是 foo 调用时的 this,不是 window,也不是 undefined
}
foo.call(obj); // 输出 'Bob'这里 arrow 的 this 来自 foo 被 call(obj) 调用时的 this,而不是 arrow() 自己的调用方式。
不复杂但容易忽略

















