this在运行时根据调用方式动态确定:默认绑定指向全局对象或undefined,隐式绑定指向调用对象,显式绑定由call/apply/bind指定,new绑定指向新实例,优先级为new>显式>隐式>默认,箭头函数无this,继承外层作用域。
this 不是函数定义时绑定的,而是在函数**运行时**根据调用方式动态确定的。它指向谁,完全取决于函数怎么被调用,而不是怎么被声明。
当函数以普通方式调用(非方法、非 new、非 call/apply/bind),this 的绑定就走默认规则:
this 指向 window(浏览器)或 global(Node.js)this 是 undefined
function foo() {
console.log(this);
}
foo(); // 非严格模式 → window;严格模式 → undefined
当函数被“点”着调用(obj.method()),this 自动绑定到点号左边的对象:
a.b.c.method() 中 this 指向 c
const obj = {
name: 'Alice',
say() { console.log(this.name); }
};
obj.say(); // 'Alice' —— this 指向 obj
const fn = obj.say;
fn(); // undefined(严格模式)—— this 不再指向 obj
这三个方法都能手动传入第一个参数作为 this 值:
func.call(obj, arg1, arg2):立即执行,参数逐个传func.apply(obj, [arg1, arg2]):立即执行,参数用数组传const bound = func.bind(obj):返回新函数,this 被永久锁定为 obj
注意:bind 返回的函数无法再被其他 call/apply 覆盖 this(硬绑定优先级最高)。
用 new 调用函数时,引擎会自动:
__proto__ 指向函数的 prototype
this 绑定到这个新对象return 对象,则默认返回 this
function Person(name) {
this.name = name; // this 指向 new 出来的实例
}
const p = new Person('Bob');
console.log(p.name); // 'Bob'
四种绑定规则有明确优先级:new 绑定 > 显式绑定 > 隐式绑定 > 默认绑定。箭头函数不遵循以上任何规则——它没有自己的 this,而是沿用外层函数作用域的 this 值,这点最容易被忽略。