this 关键字与箭头函数
约 445 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › 函数与作用域 › this 关键字与箭头函数
this 绑定规则
默认绑定
function showThis() {
console.log(this); // 非严格模式:window / 严格模式:undefined
}
showThis();隐式绑定
const user = {
name: '张三',
greet() {
console.log(this.name); // this → user
}
};
user.greet(); // "张三"显式绑定
function greet() {
console.log(`你好,${this.name}`);
}
const user1 = { name: '张三' };
const user2 = { name: '李四' };
greet.call(user1, arg1, arg2); // "你好,张三"
greet.apply(user2, [arg1, arg2]); // "你好,李四"
const boundGreet = greet.bind(user1);
boundGreet(); // "你好,张三"new 绑定
function Person(name) {
this.name = name;
}
const p = new Person('张三');
console.log(p.name); // "张三"箭头函数
// 简写语法
const add = (a, b) => a + b;
const square = x => x * x;
const noParam = () => 42;
// 返回值是对象时需加括号
const getObj = () => ({ name: '张三' });箭头函数的 this
箭头函数没有自己的 this,其 this 继承自外层作用域:
const obj = {
name: '张三',
greet() {
setTimeout(() => {
console.log(this.name); // "张三"(箭头函数继承外层的 this)
}, 100);
}
};
// 对比:普通函数
const obj2 = {
name: '李四',
greet() {
setTimeout(function() {
console.log(this.name); // undefined(this 指向 window/undefined)
}, 100);
}
};箭头函数不能用的情况
// 1. 不能作为构造函数
// const F = () => {};
// new F(); // ❌ 报错
// 2. 没有 arguments
const fn = () => {
// console.log(arguments); // ❌ 报错
};
// 3. 不适合作为对象方法
const obj = {
name: '张三',
greet: () => {
console.log(this.name); // undefined(this 不指向 obj)
}
};优先级
// new 绑定 > 显式绑定 > 隐式绑定 > 默认绑定
function foo() { console.log(this); }
const obj = { foo };
// new foo() > foo.call(obj) > obj.foo()小结
| 绑定方式 | 规则 | 示例 |
|---|---|---|
| 默认 | window / undefined | fn() |
| 隐式 | 调用者 | obj.fn() |
| 显式 | 指定对象 | fn.call(obj) |
| new | 新实例 | new Fn() |
| 箭头函数 | 外层 this | () => {} |
