function vs const 定义函数的区别

function vs const 定义函数的区别

在 JavaScript 中,我们可以使用 function 关键字const + 箭头函数 (=>) 来定义函数,它们在作用域、提升(Hoisting)、this 绑定等方面有所不同。


1️⃣ 语法区别

// 使用 function 关键字定义函数
function sayHello() {
  console.log("Hello!");
}

// 使用 const + 箭头函数定义函数
const sayHelloArrow = () => {
  console.log("Hello!");
};

区别

  • function 声明(Function Declaration)
  • const + 箭头函数是 函数表达式(Function Expression)

2️⃣ 作用域(Hoisting 提升)

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 定义的函数 不会被提升,必须在声明后才能调用

3️⃣ 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

4️⃣ 是否可以 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 绑定)!

你可能感兴趣的:(前端基础知识,javascript,前端,开发语言)