ES6箭头函数和普通函数的区别
- User
ES6箭头函数和普通函数的区别
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
ES6箭头函数和普通函数的区别
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
ES6 箭头函数与普通函数主要有以下核心区别:
this 的绑定方式this,继承外层作用域的 this(词法绑定)。
const obj = {
value: 42,
foo: () => {
console.log(this.value); // undefined(严格模式下)
}
};
obj.foo(); // this 指向外层(如 window/global 或 undefined)
this,根据调用方式动态绑定。
const obj = {
value: 42,
bar() {
console.log(this.value); // 42
}
};
obj.bar(); // this 指向 obj
arguments 对象arguments 对象,需用 ...args 替代。
const arrowFunc = (...args) => {
console.log(args); // [1, 2, 3]
};
arrowFunc(1, 2, 3);
arguments。
function normalFunc() {
console.log(arguments); // { 0: 1, 1: 2, 2: 3 }
}
normalFunc(1, 2, 3);
new 调用。
const Foo = () => {};
const obj = new Foo(); // TypeError: Foo is not a constructor
function Person(name) {
this.name = name;
}
const p = new Person("Alice"); // 正确
prototype)属性prototype 属性。
const arrowFunc = () => {};
console.log(arrowFunc.prototype); // undefined
prototype 属性。
function NormalFunc() {}
console.log(NormalFunc.prototype); // { constructor: ... }
function* 语法)。function* generator() {
yield 1;
}
super 关键字super,继承自外层。
class Parent {
method() { return "Parent"; }
}
class Child extends Parent {
arrow = () => {
console.log(super.method()); // 合法(继承外层的 super)
}
}
super。
class Child extends Parent {
method() {
console.log(super.method()); // 合法
}
}
call/apply 的行为this 不会被 call/apply 改变,但参数仍可传递。
const arrow = () => console.log(this);
arrow.call({}); // this 仍为外层上下文
this 会被 call/apply 显绑定。
function normal() {
console.log(this);
}
normal.call({}); // this 指向 {}
this 的场景(如回调函数、Promise 链、React 组件方法)。this、作为构造函数、使用 arguments 或生成器时。通过理解这些区别,可以避免因 this 指向错误或误用构造函数导致的 bug。