function
vs const
定义函数的区别在 JavaScript 中,我们可以使用 function
关键字 和 const
+ 箭头函数 (=>
) 来定义函数,它们在作用域、提升(Hoisting)、this
绑定等方面有所不同。
// 使用 function 关键字定义函数
function sayHello() {
console.log("Hello!");
}
// 使用 const + 箭头函数定义函数
const sayHelloArrow = () => {
console.log("Hello!");
};
区别:
function
声明(Function Declaration)const
+ 箭头函数是 函数表达式(Function Expression)function
会被提升(Hoisted)greet(); // ✅ 可以调用,函数被提升
function greet() {
console.log("Hello, World!");
}
function
声明的函数 在 JavaScript 解析时会被提升,所以可以在声明前调用。const
+ 箭头函数不会提升sayHi(); // ❌ ReferenceError: Cannot access 'sayHi' before initialization
const sayHi = () => {
console.log("Hi!");
};
const
定义的函数 不会被提升,必须在声明后才能调用。this
绑定function
关键字的 this
function
关键字定义的普通函数,this
指向调用它的对象。const obj = {
name: "Alice",
greet: function () {
console.log(this.name); // this 指向 obj
},
};
obj.greet(); // 输出: Alice
this
this
,它的 this
继承自外部作用域。const obj = {
name: "Alice",
greet: () => {
console.log(this.name); // ❌ this 不是 obj,而是全局对象(undefined)
},
};
obj.greet(); // 输出: undefined
✅ 如何修正? 使用 function
关键字:
const obj = {
name: "Alice",
greet: function () {
console.log(this.name);
},
};
obj.greet(); // 输出: Alice
new
关键字实例化function
可以用 new
关键字创建实例function Person(name) {
this.name = name;
}
const p = new Person("Alice");
console.log(p.name); // Alice
new
const Person = (name) => {
this.name = name;
};
const p = new Person("Alice"); // ❌ TypeError: Person is not a constructor
this
绑定,不能作为构造函数使用。区别 | function 关键字 |
const + 箭头函数 |
---|---|---|
提升(Hoisting) | ✅ 提升,可在声明前调用 | ❌ 不提升,必须先声明后调用 |
this 绑定 |
调用对象(动态绑定) | 继承外部作用域的 this |
构造函数 | ✅ 可以用 new 创建对象 |
❌ 不能用 new |
适合场景 | 传统函数、对象方法、构造函数 | 回调函数、匿名函数、this 继承 |
✅ 使用 function
:
this
指向调用对象(如对象方法)。new
关键字创建实例。✅ 使用箭头函数:
this
(避免 this
绑定问题)。map
, filter
, setTimeout
。⚡ 一般情况下,推荐优先使用 const
+ 箭头函数,除非需要 function
关键字的特性(如 this
绑定)!