JavaScript中this指向函数被调用时的执行上下文对象,非定义时决定:普通调用下严格模式为undefined、非严格模式为全局对象;对象方法调用时指向调用者对象;call/apply/bind可显式绑定;箭头函数无this,继承外层词法作用域;new调用时指向新创建实例。

JavaScript中的this指向**函数被调用时的执行上下文对象**,不是定义时决定的,而是运行时动态绑定的——这正是它“动态性”的核心。
普通函数调用:this 指向全局对象(非严格模式)或 undefined(严格模式)
直接调用函数(如 foo()),不通过任何对象或关键字触发时,this 的绑定完全取决于是否启用严格模式:
示例:
function say() { console.log(this); }say(); // 非严格模式 → window;严格模式 → undefined
对象方法调用:this 指向调用该方法的对象
当函数作为对象的属性被调用(即 obj.method()),this 指向点号前的那个对象(即 obj):
立即学习“Java免费学习笔记(深入)”;
const user = { name: 'Alice', greet() { console.log(`Hello, ${this.name}`); } };user.greet(); // Hello, Alice → this 指向 user
注意:一旦把方法单独提取出来,就失去对象绑定,变成普通调用,this 会失效:
fn(); // Hello, undefined → this 不再是 user
显式绑定:call、apply、bind 强制指定 this
这三个方法允许你手动传入一个对象,让函数内部的 this 指向它:
-
func.call(obj, arg1, arg2)—— 立即执行,参数逐个传 -
func.apply(obj, [arg1, arg2])—— 立即执行,参数以数组形式传 -
const bound = func.bind(obj)—— 返回新函数,永久绑定this为obj
这是解决“方法提取后 this 丢失”最常用的方式,比如事件回调或定时器中:
setTimeout(user.greet.bind(user), 100); // 正确输出 Hello, Alice箭头函数:没有自己的 this,沿用外层作用域的 this
箭头函数不创建自己的执行上下文,它的 this 是词法继承的——定义时所在函数作用域的 this 值,之后永远不会变:
name: 'Bob',
regular() { console.log(this.name); },
arrow: () => console.log(this.name)
};
obj.regular(); // Bob
obj.arrow(); // undefined(外层 this 是全局,没有 name)
但如果在普通函数内定义箭头函数,它就能“捕获”那个函数的 this:
name: 'Charlie',
init() {
const arrow = () => console.log(this.name);
arrow(); // Charlie
}
};
构造函数与 new:this 指向新创建的实例
用 new 调用函数时,JS 引擎会自动创建空对象,并将 this 绑定到该对象上,最后返回它(除非显式返回其他对象):
this.name = name;
}
const p = new Person('David'); // this 指向新生成的 p 实例










