Стрелочные функции были представлены в ES6.
Стрелочные функции позволяют нам писать более короткий синтаксис функции:
let myFunction = (a, b) => a * b;Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
let myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>
</body>
</html>
hello = function() {
return "Hello World!";
}Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>This example shows the syntax of a function, without the use of arrow function syntax.</p>
<p id="demo"></p>
<script>
let hello = "";
hello = function() {
return "Hello World!";
}
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
hello = () => {
return "Hello World!";
}Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
let hello = "";
hello = () => {
return "Hello World!";
}
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
Оно становится короче! Если функция имеет только один оператор, а оператор возвращает значение, вы можете удалить скобки и Ключевое слово return:
hello = () => "Hello World!";Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows an Arrow Function without the brackets or the return keyword.</p>
<p id="demo"></p>
<script>
let hello = "";
hello = () => "Hello World!";
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
Примечание. Это работает, только если у функции есть только один заявление.
Если у вас есть параметры, вы передаете их в круглых скобках:
hello = (val) => "Hello " + val;Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows an Arrow Function with a parameter.</p>
<p id="demo"></p>
<script>
let hello = "";
hello = (val) => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>
Фактически, если у вас только один параметр, вы также можете пропустить круглые скобки:
hello = val => "Hello " + val;Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows that if you have only one parameter in an Arrow Function, you can skip the parentheses.</p>
<p id="demo"></p>
<script>
let hello = "";
hello = val => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>
этого?Обработка this в стрелочных функциях также отличается от обычной функции.
Короче говоря, с помощью стрелочных функций нет привязки это.
В обычных функциях ключевое слово this представляет объект, вызвавший функцию. функция, которая может быть окном, документом, кнопкой или чем-то еще.
При использовании стрелочных функций ключевое слово this always представляет возразить, что определил стрелочную функцию.
Давайте рассмотрим два примера, чтобы понять разницу.
Оба примера вызывают метод дважды: сначала при загрузке страницы, а затем еще раз. когда пользователь нажимает кнопку.
В первом примере используется обычная функция, а во втором примере — функция стрелки.
Результат показывает, что первый пример возвращает два разных объекта (окно и кнопку). и второй пример возвращает объект окна дважды, поскольку объект окна является «владелец» функции.
В обычной функции это представляет объект, который вызывает функцию:
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML
+= this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the
function:
document.getElementById("btn").addEventListener("click", hello);Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript "this"</h1>
<p>This example demonstrate that in a regular function, the "this" keyword represents different objects depending on how the function was called.</p>
<p>Click the button to execute the "hello" function again, and you will see that this time "this" represents the button object.</p>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
let hello = "";
hello = function() {
document.getElementById("demo").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
С помощью функции стрелки это представляет владелец функции:
// Arrow Function:
hello = () => {
document.getElementById("demo").innerHTML
+= this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the
function:
document.getElementById("btn").addEventListener("click", hello);Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript "this"</h1>
<p>This example demonstrate that in Arrow Functions, the "this" keyword represents the object that owns the function, no matter who calls the function.</p>
<p>Click the button to execute the "hello" function again, and you will see that "this" still represents the window object.</p>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
let hello = "";
hello = () => {
document.getElementById("demo").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
Помните об этих различиях, когда работаете с функциями. Иногда поведение обычных функций — это то, что вам нужно, если нет, используйте функции стрелок.
В следующей таблице указаны первые версии браузера с полной поддержкой Стрелочные функции в JavaScript:
| Chrome 45 | Edge 12 | Firefox 22 | Safari 10 | Opera 32 |
| Sep, 2015 | Jul, 2015 | May, 2013 | Sep, 2016 | Sep, 2015 |