












在 JavaScript 中,=>(箭头函数)和 function(普通函数)看起来都能定义函数,但它们在行为上有本质区别。
下面我从 语法 → this → arguments → 构造函数 → 使用场景 给你系统讲清楚。
|
对比项 |
function |
=>(箭头函数) |
|---|---|---|
|
this |
动态绑定 |
词法绑定(继承外层) |
|
arguments |
✅ 有 |
❌ 没有 |
|
constructor |
✅ 可以 |
❌ 不可以 |
|
prototype |
✅ 有 |
❌ 没有 |
|
适合 |
方法、构造函数 |
回调、短函数 |
1️⃣ function:this 由“调用方式”决定
function foo() {
console.log(this);
}
foo(); // window / global
obj.foo = foo;
obj.foo(); // obj
new foo(); // 新对象
2️⃣ 箭头函数:this 在定义时就定死了
const foo = () => {
console.log(this);
};
foo(); // 外层 this
obj.foo = foo;
obj.foo(); // 仍然是外层 this
const obj = { name: 'obj', f1() { setTimeout(function () { console.log(this.name); // undefined }, 100); }, f2() { setTimeout(() => { console.log(this.name); // obj }, 100); } };
function→ this 变成 window
=>→ this 继承 f2
用 function当:
对象方法
构造函数
需要 arguments
需要 prototype
用 =>当:
回调函数
定时器
Promise / async
想锁定 this
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。