JavaScript

Чем стрелочная функция отличается от обычной?

Стрелочные vs обычные функции

Ключевые отличия

ОбычнаяСтрелочная
thisДинамическийЛексический (из окружения)
argumentsЕстьНет
prototypeЕстьНет
newМожноTypeError
Метод объектаПодходитНе подходит

this

// Обычная - this зависит от вызова
const obj = {
  value: 42,
  getValue: function() { return this.value }
}
obj.getValue()  // 42

// Стрелочная - this из лексического окружения
const obj2 = {
  value: 42,
  getValue: () => this.value  // this === window/undefined!
}
obj2.getValue()  // undefined

arguments

function regular() {
  console.log(arguments)  // Arguments [1, 2, 3]
}
regular(1, 2, 3)

const arrow = () => {
  console.log(arguments)  // ReferenceError или внешний arguments
}
arrow(1, 2, 3)

// Замена arguments в стрелочных:
const arrow2 = (...args) => console.log(args)  // [1, 2, 3]

new

function Person(name) { this.name = name }
const p = new Person("Иван")  // ✅

const Arrow = (name) => { this.name = name }
const a = new Arrow("Иван")  // ❌ TypeError: Arrow is not a constructor

Когда использовать

  • Стрелочная: колбэки, работа с массивами (map, filter), когда нужен лексический this (обработчики в классах).
  • Обычная: методы объектов/классов, функции-конструкторы, когда нужен динамический this или arguments.

Источники