在JavaScript中,this的指向并不是在编写时确定的,而是在函数被调用时根据调用方式动态绑定的。理解JS如何实现this绑定,关键在于掌握几种常见的this指向规则。

一、默认绑定
当函数以独立形式调用,没有任何修饰对象时,会触发默认绑定。在非严格模式下,this指向全局对象;在严格模式下,this为undefined。
function showThis() {
console.log(this); // 非严格模式指向window,严格模式为undefined
}
showThis();
二、隐式绑定
当函数作为对象的方法被调用时,this指向调用该方法的对象,这称为隐式绑定。
const obj = {
name: '张三',
say() {
console.log(this.name);
}
};
obj.say(); // 输出 张三,this指向obj
三、显式绑定
通过call、apply、bind方法,可以手动指定函数执行时的this值,这就是显式绑定。
- call:立即调用,参数逐个传入
- apply:立即调用,参数以数组形式传入
- bind:返回一个绑定了this的新函数,不立即调用
function greet(age) {
console.log(this.name + ' ' + age);
}
const user = { name: '李四' };
greet.call(user, 20); // 李四 20
greet.apply(user, [25]); // 李四 25
const bound = greet.bind(user);
bound(30); // 李四 30
四、new绑定
使用new调用构造函数时,JS会创建一个新对象,并将this绑定到该新对象上。
function Person(name) {
this.name = name;
}
const p = new Person('王五');
console.log(p.name); // 王五
五、箭头函数中的this
箭头函数没有自己的this,它的this继承自外层作用域,且无法通过call、apply、bind修改。
const group = {
name: '团队',
members: ['A', 'B'],
print() {
this.members.forEach(() => {
console.log(this.name); // 继承print的this,指向group
});
}
};
group.print();
六、绑定优先级
当多条规则同时出现时,优先级从高到低为:new绑定 > 显式绑定 > 隐式绑定 > 默认绑定。箭头函数始终使用词法this,不受上述优先级影响。
| 规则类型 | this指向 |
|---|---|
| 默认绑定 | 全局对象或undefined |
| 隐式绑定 | 调用对象 |
| 显式绑定 | 指定对象 |
| new绑定 | 新创建实例 |
| 箭头函数 | 外层作用域this |
掌握以上JS中this的绑定方式和指向规则,就能在开发中准确判断this的值,避免常见的指向错误。