javascript 中箭头函数的作用

Ivan Lv6

javascript 中箭头函数的作用

消除二义性

javascript 中函数可以既当构造函数使用, 也可以当普通函数使用

1
2
3
4
5
6
function fn() {
...
}

new fn(); // valid
fn(); // valid

这个时候 this 的指向是动态不确定的, 例如在当作构造函数使用时, this 指向 obj 本身, 但是当作为函数调用时, this 指向全局对象, 浏览器里是 window, nodejs 中是 global.

为了消除这种二义性, ES6 引入了 class 以及箭头函数

1
2
3
4
5
6
7
8
9
10
11
class fn {
...
}

new fn(); // valid
fn(); // invalid


const fn = () => {...}
new fn(); // invalid
fn(); // valid

通过语法限制使用 new 关键字调用函数, 以及直接调用类. 同时修正了类中和函数中的 this.

类中的 this 指向对象本身, 但是函数中的 this 指向其父级定义域中的 this

Vite 核心概念

vite 将 esbuild 和 rollup 结合在一起, 使用 esbuild 快速搭建开发服务器, 使用 rollup 用于构建打包.

  • Title: javascript 中箭头函数的作用
  • Author: Ivan
  • Created at : 2025-09-03 00:00:00
  • Updated at : 2026-10-23 18:02:31
  • Link: https://ivanfan-van.github.io/2025/09/03/note-4-evergreen-008/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
javascript 中箭头函数的作用