Windows        14.01.2024   

Введение в стрелочные функции (arrow functions) в JavaScript ES6. О ключевом слове «this» языка JavaScript: особенности использования с пояснениями «Прокидывание» контекста между несколькими вызовами

Всем привет! В этой статье мы рассмотрим, что такое стрелочные функции в ES6 и как их использовать .

Стрелочные функции – это функции, которые записываются при помощи оператора "стрелка"(=> ).

Давайте сразу рассмотрим пример:

Let add = (x, y) => x + y;
console.log(add(5, 2));

В результате выполнения данной функции в консоли мы увидим число 7.

Сначала, в круглых скобках мы передаем аргументы, далее ставим знак стрелочки, а потом пишем код самой функции. В нашем случае она просто принимает два числа и складывает их. По идее, это то же самое, что и function expression в ES5 . Если вы используете Babel или подобные компиляторы, то, скорее всего, они напишут что-то вроде этого:

Var add = function add(x, y) {
return x + y;
};

Если ваша функция принимает только один параметр, круглые скобки ставить необязательно.

Let square = x => x*x;

Такая функция принимает только один аргумент и возводит переданное число в квадрат.

Функция без параметров:

Let func = () => 77;

Если ваша функция содержит в себе несколько строк, то, во-первых, нужно использовать фигурные скобки, а во-вторых, обязательно написать, что функция возвращает, т.е. использовать ключевое слово return .

Let multiply = (x, y) => {
let result = x*y;
return result;
};

Если вам нужно вернуть литерал объекта, то его нужно обернуть в круглые скобки:

Let getObject = () => ({ brand: "BMW" });

Самовызывающаяся функция выглядит следующим образом.

  • Перевод

“Толстые” стрелочные функции (=>), так же известные, как arrow функции – абсолютно новая функциональность в ECMAScript 2015 (ранее известном под именем ES6). Если верить слухам, то в ECMAScript 2015 => синтаксис стал использоваться вместо –> синтаксиса под влиянием CoffeeScript . Так же, не последнюю роль сыграла похожесть передачи контекста this.

У стрелочных функций есть две главные задачи: обеспечить более лаконичный синтаксис; обеспечить передачу лексического this с родительским scope. Давайте детально рассмотрим каждую из них!

Новый синтаксис функций
Классический синтаксис функций в JavaScript отличается ригидностью, будь это функция с одной переменной или страница с множеством функций. При каждом объявлении функци, вам необходимо писать function () {}. Потребность в более лаконичном синтаксисе функций была одной из причин, почему в свое время CoffeeScript стал очень популярен. Эта потребность особенно очевидна в случае с небольшими callback функциями. Давайте просто взглянем на цепочку Promise:
function getVerifiedToken(selector) { return getUsers(selector) .then(function (users) { return users; }) .then(verifyUser) .then(function (user, verifiedToken) { return verifiedToken; }) .catch(function (err) { log(err.stack); }); }
Вверху вы видите более или менее удобоваримый код, написанный с использованием классического синтаксиса function в JavaScript. А вот так выглядит тот же самый код, переписанный с использованием стрелочного синтаксиса:
function getVerifiedToken(selector) { return getUsers(selector) .then(users => users) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack)); }
Здесь надо обратить внимание на несколько важных моментов:
  • Мы потеряли function и {}, потому что наши callback функции записываются в одну строку.
  • Мы убрали (). Теперь они не обертывают список аргументов, когда присутствует только один аргумент (остальные аргументы проходят как исключения; например, (...args) => ...).
  • Мы избавились от ключевого слова return. Убирая {}, мы позволяем однострочным стрелочным функциям провести неявный возврат (в других языках такие функции часто называют лямбда функциями).
Еще раз обратим внимание на последний пункт. Неявный возврат происходит только в случае с однострочными стрелочными функциями. Когда стрелочная функция определяется с {}, даже если она является отдельным оператором, неявный возврат не происходит.
const getVerifiedToken = selector => { return getUsers() .then(users => users) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack)); }
Здесь начинается самое интересное. Так как у нашей функции есть только один оператор, мы можем убрать {}, и код будет очень похож на синтаксис CoffeeScript :
const getVerifiedToken = selector => getUsers() .then(users => users) .then(verifyUser) .then((user, verifiedToken) => verifiedToken) .catch(err => log(err.stack));
И все же код выше написан с использованием синтаксиса ES2015. (Я тоже удивился, что он прекрасно скомпилировался .) Когда мы говорим о стрелочных функциях с одним оператором, это не значит, что оператор не может занимать больше одной строки, для удобства использования.

Есть, однако, один существенный минус: убрав {} из стрелочных функций, как мы можем возвратить пустой объект? Например, тот же {}?
const emptyObject = () => {}; emptyObject(); // ?
А вот как выглядит весь код вместе:
function () { return 1; } () => { return 1; } () => 1 function (a) { return a * 2; } (a) => { return a * 2; } (a) => a * 2 a => a * 2 function (a, b) { return a * b; } (a, b) => { return a * b; } (a, b) => a * b function () { return arguments; } (...args) => args () => {} // undefined () => ({}) // {}

Лексический this
История о том, как this пытались протащить в JavaScript, уже покрылась пылью. Каждая function в JavaScript задает свой собственный контекст для this. Этот контекст, с одной стороны, очень легко обойти, а, с другой стороны, он крайне раздражает. На примере ниже вы видите код для часов, которые обновляют данные каждую секунду, обращаясь к jQuery:
$(".current-time").each(function () { setInterval(function () { $(this).text(Date.now()); }, 1000); });
При попытке сослаться на this DOM элемента, заданный через each в callback’е setInterval, мы, к сожалению, получаем совсем другой this, – тот, который принадлежит callback. Обойти этот момент можно, задав переменную that или self:
$(".current-time").each(function () { var self = this; setInterval(function () { $(self).text(Date.now()); }, 1000); });
“Толстые” стрелочные функции могут помочь решить эту проблему, так как они не имеют this:
$(".current-time").each(function () { setInterval(() => $(this).text(Date.now()), 1000); });
Как насчет аргументов?
Одним из минусов стрелочных функций является то, что у них нет собственной переменной arguments, как у обычных функций:
function log(msg) { const print = () => console.log(arguments); print(`LOG: ${msg}`); } log("hello"); // hello
Повторимся, что у стрелочных функций нет this и нет arguments. Однако, приняв это во внимание, вы все же можете получить аргументы, переданные в стрелочные функции с помощью rest-параметров (так же известны, как spread операторы):
function log(msg) { const print = (...args) => console.log(args); print(`LOG: ${msg}`); } log("hello"); // LOG: hello
Как насчет генераторов?
“Толстые” стрелочные функции не могут использоваться как генераторы. Никаких исключений и обходных путей нет. Точка.
Вывод
“Толстые” стрелочные функции – одна из причин, почему я так люблю JavaScript. Очень соблазнительно просто начать использовать => вместо function. Я видел целые библиотеки, где используется только вариант =>. Не думаю, однако, что это разумно. В конце концов, у => есть много особенностей и скрытых функций. Я рекомендую использовать стрелочные функции только там, где вам нужна новая функциональность:
  • Функции с одиночными операторами, которые сразу же делают возврат;
  • функции, которые должны работать с this с родительским scope.
ES6 сегодня
Так можно ли воспользоваться возможностями ES6 уже сегодня? Использование транспайлеров стало нормой в последние несколько лет. Ни простые разработчики, ни крупные компании не стесняются их применять.

An arrow function expression is a syntactically compact alternative to a regular function expression , although without its own bindings to the this , arguments , super , or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

Syntax

Basic syntax

(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // equivalent to: => { return expression; } // Parentheses are optional when there"s only one parameter name: (singleParam) => { statements } singleParam => { statements } // The parameter list for a function with no parameters should be written with a pair of parentheses. () => { statements }

Advanced syntax

// Parenthesize the body of a function to return an object literal expression: params => ({foo: bar}) // Rest parameters and default parameters are supported (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // Destructuring within the parameter list is also supported var f = ( = , {x: c} = {x: a + b}) => a + b + c; f(); // 6

Description

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

Shorter functions

var elements = [ "Hydrogen", "Helium", "Lithium", "Beryllium" ]; // This statement returns the array: elements.map (function(element) { return element.length; }); // The regular function above can be written as the arrow function below elements.map((element) => { return element.length; }); // // When there is only one parameter, we can remove the surrounding parentheses elements.map (element => { return element.length; }); // // When the only statement in an arrow function is `return`, we can remove `return` and remove // the surrounding curly brackets elements.map(element => element.length); // // In this case, because we only need the length property, we can use destructuring parameter: // Notice that the `length` corresponds to the property we want to get whereas the // obviously non-special `lengthFooBArX` is just the name of a variable which can be changed // to any valid variable name you want elements.map (({ length:lengthFooBArX }) => lengthFooBArX); // // This destructuring parameter assignment can also be written as seen below. However, note that in // this example we are not assigning `length` value to the made up property. Instead, the literal name // itself of the variable `length` is used as the property we want to retrieve from the object. elements.map (({ length }) => length); //

No separate this

Before arrow functions, every new function defined its own this value based on how the function was called:

  • A new object in the case of a constructor.
  • undefined in strict mode function calls.
  • The base object if the function was called as an "object method".

This proved to be less than ideal with an object-oriented style of programming.

Function Person() { // The Person() constructor defines `this` as an instance of itself. this.age = 0; setInterval(function growUp() { // In non-strict mode, the growUp() function defines `this` // as the global object (because it"s where growUp() is executed.), // which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } var p = new Person();

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

Function Person() { var that = this; that.age = 0; setInterval(function growUp() { // The callback refers to the `that` variable of which // the value is the expected object. that.age++; }, 1000); } "use strict"; var obj = { a: 10 }; Object.defineProperty(obj, "b", { get: () => { console.log(this.a, typeof this.a, this); // undefined "undefined" Window {...} (or the global object) return this.a + 10; // represents global object "Window", therefore "this.a" returns "undefined" } });

Use of the new operator

Arrow functions cannot be used as constructors and will throw an error when used with new .

Var Foo = () => {}; var foo = new Foo(); // TypeError: Foo is not a constructor

Use of prototype property

Arrow functions do not have a prototype property.

Var Foo = () => {}; console.log(Foo.prototype); // undefined

Use of the yield keyword

The yield keyword may not be used in an arrow function"s body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

Function body

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

Var func = x => x * x; // concise body syntax, implied "return" var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed

Returning object literals

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

Var func = () => { foo: 1 }; // Calling func() returns undefined! var func = () => { foo: function() {} }; // SyntaxError: function statement requires a name

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

You must wrap the object literal in parentheses:

Var func = () => ({ foo: 1 });

Line breaks

An arrow function cannot contain a line break between its parameters and its arrow.

Var func = (a, b, c) => 1; // SyntaxError: expected expression, got "=>"

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

Var func = (a, b, c) => 1; var func = (a, b, c) => (1); var func = (a, b, c) => { return 1 }; var func = (a, b, c) => 1; // no SyntaxError thrown

Parsing order

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

Let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments callback = callback || (() => {}); // ok

More examples

// An empty arrow function returns undefined let empty = () => {}; (() => "foobar")(); // Returns "foobar" // (this is an Immediately Invoked Function Expression) var simple = a => a > 15 ? 15: a; simple(16); // 15 simple(10); // 10 let max = (a, b) => a > b ? a: b; // Easy array filtering, mapping, ... var arr = ; var sum = arr.reduce((a, b) => a + b); // 66 var even = arr.filter(v => v % 2 == 0); // var double = arr.map(v => v * 2); // // More concise promise chains promise.then(a => { // ... }).then(b => { // ... }); // Parameterless arrow functions that are visually easier to parse setTimeout(() => { console.log("I happen sooner"); setTimeout(() => { // deeper code console.log("I happen later"); }, 1); }, 1);

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of "Arrow Function Definitions" in that specification.
Draft

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Arrow functions Chrome Full support 45 Edge Full support Yes Firefox Full support 22

Notes

Full support 22

Notes

Notes Prior to Firefox 39, a line terminator (\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \n =>
IE No support No Opera Full support 32 Safari Full support 10 WebView Android Full support 45 Chrome Android Full support 45 Firefox Android Full support 22

Notes

Full support 22

Notes

Notes The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of "use strict"; is now required. Notes Prior to Firefox 39, a line terminator (\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \n => {} will now throw a SyntaxError in this and later versions.
Opera Android Full support 32 Safari iOS Full support 10 Samsung Internet Android Full support 5.0 nodejs Full support Yes
Trailing comma in parameters Chrome Full support 58 Edge ? Firefox Full support 52 IE No support No Opera Full support 45 Safari ? WebView Android Full support 58 Chrome Android Full support 58 Firefox Android Full support 52 Opera Android Full support 43 Safari iOS ? Samsung Internet Android Full support 7.0 nodejs Full support Yes

Legend

Full support Full support No support No support Compatibility unknown Compatibility unknown See implementation notes. See implementation notes.

Они стали очень модными, мы видим их во всех новых статьях. И, если вы не привыкли к ним, вам будет трудно понимать современный (на ES6) код, содержащий стрелочные функции.

Данная статья не направлена на то, чтобы сказать, когда и как их использовать. Я только попытаюсь объяснить новый синтаксис для тех, кто видит его в первый раз. Будете вы его использовать или нет, - не важно, но рано или поздно вы все равно столкнетесь с ним где-нибудь. Так что лучше понимать механику этого нового синтаксиса.

Вот небольшой пример:

Const addOne = function(n) { return n + 1; }

Приведенный выше код можно записать так:

Const addOne = (n) => { return n + 1; }

Или, в данном случае, еще короче:

Const addOne = (n) => n + 1;

Второй пример использует { ... } фигурные скобки, но, поскольку, в нем всего одна строка кода, фигурные скобки могут быть опущены и возврат подразумевается сам собой, как видно из третьего примера.

Один параметр

Когда стрелочная функция имеет один параметр, скобки можно опустить:

// Было: someCallBack((results) => { ... }) // Стало: someCallBack(results => { ... })

Но, если нет никаких параметров, вы должны использовать открывающую и закрывающую скобки:

SomeCallBack(() => { ... })

Функции обратного вызова

Стрелки функции особенно полезны для обратных вызовов. Те, кто знаком с JavaScript, знакомы с его лексической областью видимости, которая довольно хороша, но может проделывать такие трюки как этот (this ):

Var _this = this; someCallBack(function() { _this.accessOuterScope(); })

Существует несколько вариаций этого «_this» (например, «self» или «that»), но идея та же. В функциях обратного вызова нам нужен доступ к версии внешней области видимости, но идея та же. В функциях обратного вызова нам нужен доступ к версии внешней области видимости this , которая теперь отличается от предыдущей, поскольку мы говорим о функции обратного вызова.

С помощью стрелочных функций , мы получаем "block scope" (блочную область видимости) и «this», которые являются одним и тем же «this» в обоих случаях. Это означает, что код сверху можно переписать без _this = this:

SomeCallBack(() => { this.accessOuterScope(); })

"Обертка"

Давайте представим ситуацию, как в React, где событие onClick должно вызывать doSomething() , (), но также должно передавать аргументы в doSomething() (например ID). Этот пример на самом деле не работает:

Некий юзер
} })

Код запустится, но технически он будет вызывать doSomething() сразу же при загрузке страницы. Чтобы решить эту проблему, некоторые разработчики ссылаются на функцию-обертку:

Const User = React.createClass(function() { render: function() { return

Некий юзер
}, onClick: function() { doSomething(this.props.userId); } })

Отсутствие круглой скобки в this.onClick означает, что это просто отсылка к функции, а не вызов ее.

Функция onClick() теперь является чем-то вроде «обертки» для doSomething() . Со стрелочными функциями можно делать «обертки» такого типа:

Const User = React.createClass(function() { render: function() { return

doSomething(this.props.userId)}>Некий юзер
} })

Как альтернативу, - мы могли бы также использовать.bind() , который не требует никаких оберток (стрелочных функций и прочего):

Const User = React.createClass(function() { render: function() { return

Некий юзер
} })

Браузерная поддрержка стрелочных функций

Если вам нужна поддержка браузеров помимо последних версий Chrome и Firefox , воспользуйтесь Babel транспайлер , чтобы конвертировать написанный вами ES6-код в ES5.