javascript 中 this 的绑定优先级从高到低依次为:new 绑定、显式绑定(call/apply/bind)、隐式绑定(对象调用)和默认绑定。具体做法是,当函数被作为方法调用时,this 指向调用它的对象;使用 call、apply 或 bind 时,this 指向指定的第一个参数;通过 new 关键字实例化时,this 指向新创建的对象;在普通函数调用或严格模式下非对象方法的调用中,this 指向全局对象(浏览器中为 window)或 undefined。

隐式绑定与显式绑定的区别是什么
隐式绑定发生在函数作为对象属性被调用时,this 自动指向该对象;显式绑定则通过 Function.prototype.call、apply 或 bind 强制指定 this 的值。显式绑定的优先级高于隐式绑定,这意味着即使函数原本属于某个对象,一旦使用 call 或 apply 调用,this 就会指向传入的第一个参数,而不是原对象。

const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
// 隐式绑定:this 指向 obj
obj.greet(); // 输出: Alice
// 显式绑定:this 指向 { name: 'Bob' }
const otherObj = { name: 'Bob' };
obj.greet.call(otherObj); // 输出: Bob
// bind 返回一个新函数,this 永久绑定
const boundGreet = obj.greet.bind(otherObj);
boundGreet(); // 输出: Bob
箭头函数中的 this 是如何确定的
箭头函数没有自己的 this 绑定,它捕获定义时所在上下文的 this 值。这意味着箭头函数的 this 既不受隐式绑定影响,也不受显式绑定或 new 调用的影响。无论在哪里调用箭头函数,其内部的 this 始终等于定义该箭头函数时外层作用域的 this 值。
立即学习“Java免费学习笔记(深入)”;

const obj = {
name: 'Alice',
regularFunc: function() {
console.log('Regular:', this.name);
},
arrowFunc: () => {
console.log('Arrow:', this.name);
}
};
obj.regularFunc(); // 输出: Regular: Alice (this 指向 obj)
obj.arrowFunc(); // 输出: Arrow: undefined (this 指向全局或 undefined)
使用 new 关键字调用构造函数时 this 指向哪里
当使用 new 关键字调用一个函数时,JavaScript 会创建一个全新的对象,并将该函数内部的 this 绑定到这个新对象上。如果构造函数没有显式返回一个对象,那么 new 表达式的结果就是这个新创建的 this 对象。这是 this 绑定中优先级最高的一种情况,它会覆盖任何隐式或显式绑定。
function Person(name) {
this.name = name;
}
const person = new Person('Charlie');
console.log(person.name); // 输出: Charlie
// 验证 this 指向新对象
console.log(person instanceof Person); // 输出: true


















