this调用
一个函数里的this应该指向上一个函数的调用?
不是的,this
并不是指向上一个函数的调用,而是指向当前函数的执行上下文(也就是调用它的对象)。这是 JavaScript 中一个常见的误区,我们来澄清一下。
✅ 正确的理解:this
的指向取决于函数的调用方式,而不是定义方式。
JavaScript 中 this
的绑定规则主要有以下几种:
1. 默认绑定(独立函数调用)
function foo() {
console.log(this); // 非严格模式下指向 window(浏览器)或 global(Node)
}
foo(); // this -> window / global
2. 隐式绑定(作为对象方法调用)
const obj = {
name: "Alice",
greet: function () {
console.log(this.name);
}
};
obj.greet(); // this -> obj,输出 "Alice"
3. 显式绑定(使用 .call()
、.apply()
、.bind()
)
function greet() {
console.log(this.name);
}
const person = { name: "Bob" };
greet.call(person); // this -> person,输出 "Bob"
4. new 绑定(构造函数)
function Person(name) {
this.name = name;
}
const p = new Person("Charlie");
console.log(p.name); // this -> 新创建的对象
5. 箭头函数(不绑定自己的 this
)
箭头函数不会创建自己的 this
,它会从外层作用域继承 this
。
const obj = {
name: "David",
greet: () => {
console.log(this.name); // this 来自外层作用域(可能是 window)
}
};
obj.greet(); // 输出 undefined(或 window.name)
❌ 错误理解:“this 指向上一个函数的调用”
这句话是不准确的,比如:
function outer() {
inner();
}
function inner() {
console.log(this); // 仍然是默认绑定,可能指向 window,而不是 outer
}
outer();
✅ 总结一句话:
this
指向的是调用当前函数的对象,而不是定义它的位置或“上一个函数”。
比如说,我一个函数内部使用了另一个函数,那么内部这个函数可以使用this调用外部函数的变量或者方法
不可以直接通过 this
来访问外层函数的局部变量或方法。
在内层函数里,this
依旧遵循前面讲的绑定规则——它只跟“当前这次调用”有关,和“我在哪个函数里被写出来”无关。外层函数的局部变量(用 let / const / var
声明的)既不是外层函数的“属性”,也不会自动挂到任何对象上,因此内层函数的 this
无论如何都不会直接指向它们。
下面用代码把几种典型场景拆开说明:
1. 独立调用:内层函数拿不到外层局部变量
function outer() {
const msg = 'hello';
function inner() {
console.log(this.msg); // undefined 或报错
console.log(msg); // ✅ 闭包访问,输出 'hello'
}
inner(); // 独立调用 → this 默认绑定为 window(非严格)或 undefined(严格)
}
outer();
inner()
作为独立函数被调用,this
不会指向outer
的局部作用域。- 想访问
msg
,只能依靠闭包(词法作用域),而不是this
。
2. 作为对象方法调用:依旧拿不到外层局部变量
function outer() {
const secret = 42;
const api = {
secret: 100,
show() {
function inner() {
console.log(this.secret); // 100,不是 42
}
inner(); // 独立调用 → this 指向 window 或 undefined
}
};
api.show(); // 最终 this.secret 是 100,而不是外层局部变量 42
}
inner()
仍然是独立调用,所以this
不会指向outer
的局部作用域。- 如果想让
inner
里用this
访问api.secret
,需要显式绑定或箭头函数(见下)。
3. 想让内层函数用 this
访问外层对象:改用箭头函数或显式绑定
3-a 箭头函数(继承外层词法作用域的 this
)
function outer() {
const obj = {
value: 10,
getValue() {
const inner = () => {
console.log(this.value); // 10
};
inner();
}
};
obj.getValue(); // this 指向 obj
}
箭头函数把 this
固定为外层 getValue
运行时所在的 this
,也就是 obj
。
3-b 显式绑定
function outer() {
const obj = { value: 20 };
function inner() {
console.log(this.value); // 20
}
inner.call(obj); // 显式把 this 绑到 obj
}
✅ 结论
- 外层函数的局部变量/常量只能通过**闭包(词法作用域)**访问,不能通过
this
。 - 想让内层函数用
this
指向某个对象,需要:- 把内层函数写成该对象的方法;
- 或者使用箭头函数继承外层
this
; - 或者用
.call / .apply / .bind
显式绑定。
一句话:this
和“函数嵌套”无关,只和“怎么被调用”有关。