this的指向由调用方式决定,共五种绑定规则:默认绑定指向全局或undefined,隐式绑定指向调用对象,显式绑定通过call/apply/bind指定,new绑定指向新实例,箭头函数词法继承外层this;优先级为new > 显式 > 隐式 > 默认。

在 JavaScript 中,this 的指向问题一直是开发者容易混淆的核心概念之一。this 的值不是由函数定义的位置决定,而是由函数的调用方式动态确定。理解 this 的绑定规则及其底层实现机制,有助于写出更稳定、可预测的代码。
1. 默认绑定:独立函数调用
当函数作为普通函数被调用时,this 指向全局对象(在浏览器中是 window,在 Node.js 中是 global)。严格模式下,默认绑定的 this 为 undefined。
注意:- 非严格模式:
function fn() { console.log(this); } fn();输出 window - 严格模式:
'use strict'; function fn() { console.log(this); }输出 undefined
2. 隐式绑定:对象方法调用
当函数作为对象的方法被调用时,this 指向该对象。
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // 输出 Alice
但要注意隐式丢失的情况:
立即学习“Java免费学习笔记(深入)”;
const greet = obj.greet; greet(); // 输出 undefined(严格模式)或全局 name(非严格)
此时 this 不再指向 obj,而是遵循默认绑定规则。
3. 显式绑定:call、apply 和 bind
通过 call、apply 或 bind 方法,可以手动指定函数执行时的 this 值。
- call/apply:立即执行函数,参数分别为列表和数组
- bind:返回一个新函数,其 this 被永久绑定
function introduce(age) {
console.log(`I'm ${this.name}, ${age} years old.`);
}
introduce.call({ name: 'Bob' }, 25); // 输出 I'm Bob, 25 years old.
const boundFn = introduce.bind({ name: 'Charlie' });
boundFn(30); // 输出 I'm Charlie, 30 years old.
4. new 绑定:构造函数调用
使用 new 调用函数时,会创建一个新对象,this 指向这个新实例。
function Person(name) {
this.name = name;
}
const p = new Person('David');
console.log(p.name); // 输出 David
new 的过程大致如下:
- 创建一个空对象
- 将构造函数的 prototype 赋给新对象的 __proto__
- 将 this 绑定到新对象并执行构造函数
- 返回新对象(除非构造函数显式返回一个对象)
5. 箭头函数:词法绑定
箭头函数没有自己的 this,它的 this 继承自外层作用域(词法环境)。
const obj = {
name: 'Eve',
normalFn: function() {
console.log(this.name);
},
arrowFn: () => {
console.log(this.name);
}
};
obj.normalFn(); // 输出 Eve
obj.arrowFn(); // 输出 undefined(this 指向外层,通常是全局或模块)
因此箭头函数不能作为构造函数使用,也无法通过 call/apply/bind 改变 this。
6. this 绑定优先级
当多种绑定规则同时存在时,优先级从高到低为:
- new 绑定
- 显式绑定(bind)
- 隐式绑定
- 默认绑定
例如,即使使用 bind 绑定了 this,new 仍会覆盖它:
function fn() { console.log(this.x); }
const bound = fn.bind({ x: 1 });
new bound(); // 输出 undefined(new 创建的新对象没有 x)
// 若构造函数返回原始值,则忽略;若返回对象,则以返回值为准
7. 实现 bind 函数
bind 的核心功能是返回一个绑定 this 的函数,并支持预设参数。可以手动实现一个简易版本:
Function.prototype.myBind = function(context, ...args) {
if (typeof this !== 'function') {
throw new Error('not a function');
}
const fn = this;
const bound = function(...innerArgs) {
// 判断是否被 new 调用
return fn.apply(
this instanceof bound ? this : context,
args.concat(innerArgs)
);
};
// 维护原型链
bound.prototype = Object.create(this.prototype);
return bound;
};
这个实现处理了 this 的正确绑定,并支持 new 调用时的优先级。
基本上就这些。掌握 this 的五种绑定规则和它们之间的优先关系,能有效避免常见错误。实际开发中建议多用箭头函数明确上下文,或使用 bind 固定关键函数的 this,提升代码可维护性。










