diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:51:47 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:51:47 +0100 |
commit | daa1a2aff136fa9da1fcc97d7da97a2036fabc77 (patch) | |
tree | 026b16ef36fc7349d94d983405ae72ef6cb42120 /files/uk/web/javascript/reference/functions/arrow_functions/index.html | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-daa1a2aff136fa9da1fcc97d7da97a2036fabc77.tar.gz translated-content-daa1a2aff136fa9da1fcc97d7da97a2036fabc77.tar.bz2 translated-content-daa1a2aff136fa9da1fcc97d7da97a2036fabc77.zip |
unslug uk: move
Diffstat (limited to 'files/uk/web/javascript/reference/functions/arrow_functions/index.html')
-rw-r--r-- | files/uk/web/javascript/reference/functions/arrow_functions/index.html | 362 |
1 files changed, 362 insertions, 0 deletions
diff --git a/files/uk/web/javascript/reference/functions/arrow_functions/index.html b/files/uk/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..f1638d8d84 --- /dev/null +++ b/files/uk/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,362 @@ +--- +title: Стрілкові функції +slug: Web/JavaScript/Reference/Functions/Стрілкові_функції +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong>Вирази стрілкових функцій </strong>мають більш короткий синтаксис, аніж <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">функціональні вирази</a> і не мають свого власного <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a>, і <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a>. Вони не можуть бути використані як конструктор і завжди анонімні.</p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<h3 id="Basic_Syntax">Basic Syntax</h3> + +<pre class="syntaxbox"><strong>(<em></em></strong><em>параметр1</em><strong><em></em></strong>,<em>параметр2</em>, …, <em>параметрN</em><strong>) => {</strong> <em>оператори</em> <strong>}</strong> +<strong>(</strong><em>параметр1</em>, <em>параметр2</em>, …, <em>параметрN</em><strong>) =></strong> <em>вираз</em> +// еквівалентно до запису: <strong>(</strong><em>параметр1</em>,<em>параметр2</em>, …, <em>параметрN</em><strong>)</strong> => { return <em>вираз</em>; } + +// Якщо у функції тільки один параметр, то дужки не обов'язкові: +<em>(параметр)</em> <strong>=> {</strong> <em>оператори</em> <strong>}</strong> +<em>параметр</em> <strong>=></strong> { <em>оператори </em>} +<em>параметр</em> <strong>=></strong> <em>вираз</em> + + +// Список параметрів для функції без параметрів повинен бути записаний у парі фігурних дужок. +() => { <em>оператори</em> } +</pre> + +<h3 id="Advanced_Syntax">Advanced Syntax</h3> + +<pre class="syntaxbox">// Візьміть тіло функції у дужки, якщо вона повертає об'єкт +<em>params</em> => ({<em>foo: bar</em>}) + +// Залишкові параметри та параметри за замовчуванням підтримуються як і в звичайних функціях +(<em>параметр1</em>, <em>параметр2</em>, <strong>...залишкові параметри</strong>) => { <em>оператори</em> } +(<em>параметр1</em> <strong>= значення_за_замовчуванням</strong>, <em>параметр2</em>, …, параметрN <strong>= значення_за_замовчуваннямN</strong>) => { <em>оператори</em> } + +// Деструктиризація в списку параметрів також підтримується: +let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); +// 6 +</pre> + +<h2 id="Опис">Опис</h2> + +<p>Див. також <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a>.</p> + +<p>Появу стрілкових функцій зумовили два фактори: можливість більш короткого запису і випадки, коли сутність <code>this</code> не обов'язкова.</p> + +<h3 id="Коротший_запис">Коротший запис</h3> + +<pre class="brush: js">var materials = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(function(material) { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>((material) => { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(material => material.length); // [8, 6, 7, 9] +</pre> + +<h3 id="Спільний_this">Спільний <code>this</code></h3> + +<p>До появи стрілкових функцій кожна нова функція мала власне значення <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> :</p> + +<ul> + <li>новий об'єкт у випадку конструктора</li> + <li>undefined для викликів функції в <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a></li> + <li>контекст об'єкту при виклику функції як методу об'єкту</li> + <li>і т. ін.</li> +</ul> + +<p>Це все було далеким від ідеалів об'єктно-орієнтованого програмування.</p> + +<pre class="brush: js">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, which is different from the `this` + // defined by the Person() constructor. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>В ECMAScript 3/5 ця проблема вирішувалась шляхом присвоєння значення <code>this</code> змінній, оголошеній всередині функції.</p> + +<pre class="brush: js">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); +}</pre> + +<p>Або можна створити <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> (прив'язану функцію), в яку передати значення <code>this</code> для функції (функція <code>growUp()</code> в прикладі вище).</p> + +<p>Стрілкова функція не має власного контексту <code>this</code>, а використовує <code>this</code> з контексту вище. Тому в коді, наведеному нижче, <code>this</code> для функції <code>setInterval</code> має таке ж значення, як і <code>this</code> зовнішньої функції:</p> + +<pre class="brush: js">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| properly refers to the person object + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Relation_with_strict_mode">Relation with strict mode</h4> + +<p>Given that <code>this</code> comes from the surrounding lexical context, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> rules with regard to <code>this</code> are ignored.</p> + +<pre class="brush: js">var f = () => { 'use strict'; return this; }; +f() === window; // or the global object</pre> + +<p>All other strict mode rules apply normally.</p> + +<h4 id="Invoked_through_call_or_apply">Invoked through call or apply</h4> + +<p>Since arrow functions do not have their own <code>this</code>, the methods <code>call()</code> or <code>apply()</code> can only pass in parameters. <code>thisArg</code> is ignored.</p> + +<pre class="brush: js">var adder = { + base: 1, + + add: function(a) { + var f = v => v + this.base; + return f(a); + }, + + addThruCall: function(a) { + var f = v => v + this.base; + var b = { + base: 2 + }; + + return f.call(b, a); + } +}; + +console.log(adder.add(1)); // This would log to 2 +console.log(adder.addThruCall(1)); // This would log to 2 still</pre> + +<h3 id="No_binding_of_arguments">No binding of <code>arguments</code></h3> + +<p>Arrow functions do not have their own <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Thus, in this example, <code>arguments</code> is simply a reference to the arguments of the enclosing scope:</p> + +<pre class="brush: js">var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // <em>foo</em>'s implicit arguments binding. arguments[0] is n + return f(10); +} + +foo(1); // 2</pre> + +<p>In most cases, using <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> is a good alternative to using an <code>arguments</code> object.</p> + +<pre class="brush: js">function foo(n) { + var f = (...args) => args[0] + n; + return f(10); +} + +foo(1); // 11</pre> + +<h3 id="Arrow_functions_used_as_methods">Arrow functions used as methods</h3> + +<p>As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:</p> + +<pre class="brush: js">'use strict'; +var obj = { + i: 10, + b: () => console.log(this.i, this), + c: function() { + console.log(this.i, this); + } +} +obj.b(); // prints undefined, Window {...} (or the global object) +obj.c(); // prints 10, Object {...}</pre> + +<p>Arrow functions do not have their own <code>this</code>. Another example involving {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js">'use strict'; +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); + return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' + } +}); +</pre> + +<h3 id="Use_of_the_new_operator">Use of the <code>new</code> operator</h3> + +<p>Arrow functions cannot be used as constructors and will throw an error when used with <code>new</code>.</p> + +<pre class="brush: js">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="Use_of_prototype_property">Use of <code>prototype</code> property</h3> + +<p>Arrow functions do not have a <code>prototype</code> property.</p> + +<pre class="brush: js">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="Use_of_the_yield_keyword">Use of the <code>yield</code> keyword</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> 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.</p> + +<h2 id="Тіло_функції">Тіло функції</h2> + +<p>Arrow functions can have either a "concise body" or the usual "block body".</p> + +<p>In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit <code>return</code> statement.</p> + +<pre class="brush: js">var func = x => x * x; +// concise body syntax, implied "return" + +var func = (x, y) => { return x + y; }; +// with block body, explicit "return" needed +</pre> + +<h2 id="Повернення_літерала_обєкта">Повернення літерала об'єкта</h2> + +<p>Keep in mind that returning object literals using the concise body syntax <code>params => {object:literal}</code> will not work as expected.</p> + +<pre class="brush: js">var func = () => { foo: 1 }; +// Calling func() returns undefined! + +var func = () => { foo: function() {} }; +// SyntaxError: function statement requires a name</pre> + +<p>This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. <code>foo</code> is treated like a label, not a key in an object literal).</p> + +<p>Remember to wrap the object literal in parentheses.</p> + +<pre class="brush: js">var func = () => ({foo: 1});</pre> + +<h2 id="Розрив_рядка">Розрив рядка</h2> + +<p>An arrow function cannot contain a line break between its parameters and its arrow.</p> + +<pre class="brush: js">var func = () + => 1; +// SyntaxError: expected expression, got '=>'</pre> + +<h2 id="Порядок_розбору">Порядок розбору</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js">let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok +</pre> + +<h2 id="Ще_приклади">Ще приклади</h2> + +<pre class="brush: js">// An empty arrow function returns undefined +let empty = () => {}; + +(() => 'foobar')(); +// Returns "foobar" +// (this is an Immediately Invoked Function Expression +// see 'IIFE' in glossary) + +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 = [5, 6, 13, 0, 1, 18, 23]; + +var sum = arr.reduce((a, b) => a + b); +// 66 + +var even = arr.filter(v => v % 2 == 0); +// [6, 0, 18] + +var double = arr.map(v => v * 2); +// [10, 12, 26, 0, 2, 36, 46] + +// 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); +</pre> + +<h2 id="Специфікації">Специфікації</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Специфікація</th> + <th scope="col">Статус</th> + <th scope="col">Коментар</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Початкова виознака.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Підтримка_веб-переглядачами">Підтримка веб-переглядачами</h2> + +<div> +<div class="hidden">Таблиця сумісності на цій сторінці створена зі структурованих даних. Якщо ви хочете долучитися до розробки цих даних, пропонуйте нам свої pull request до репозиторію <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div> + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> +</div> + +<h2 id="Див._також">Див. також</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a></li> +</ul> |