


What is the difference between arrow functions and ordinary functions in es6
Mar 08, 2022 pm 12:11 PMDifference: 1. The definition of arrow function is much simpler, clearer and faster than the definition of ordinary function; 2. The arrow function does not create its own this, but the ordinary function does; 3. The arrow function cannot be used as The constructor is used, and the arrow function can be used as a constructor; 4. The arrow function does not have its own arguments, but the arrow function does.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The arrow function is a high-frequency test point in the front-end interview. The arrow function is an API of ES6. I believe many people know it. Because its syntax is simpler than ordinary functions, it is deeply loved by everyone.
1. Basic syntax
In ES6, arrows =>
are allowed to be used to define arrow functions. The specific syntax is, Let’s look at a simple example:
// 箭頭函數(shù) let fun = (name) => { // 函數(shù)體 return `Hello ${name} !`; }; // 等同于 let fun = function (name) { // 函數(shù)體 return `Hello ${name} !`; };
It can be seen that defining arrow functions is much simpler in mathematical syntax than ordinary functions. The arrow function omits the function
keyword and uses the arrow =>
to define the function. The parameters of the function are placed in the brackets before =>
, and the function body is placed in the curly braces after =>
.
About the parameters of the arrow function:
① If the arrow function has no parameters, just write an empty bracket.
② If the arrow function has only one parameter, you can also omit the parentheses surrounding the parameter.
③ If the arrow function has multiple parameters, separate the parameters with commas (,) and wrap them in parentheses.
// 沒(méi)有參數(shù) let fun1 = () => { console.log(111); }; // 只有一個(gè)參數(shù),可以省去參數(shù)括號(hào) let fun2 = name => { console.log(`Hello ${name} !`) }; // 有多個(gè)參數(shù) let fun3 = (val1, val2, val3) => { return [val1, val2, val3]; };
About the function body of the arrow function:
① If the function body of the arrow function has only one line of code, it simply returns a variable or Returns a simple JS expression, you can omit the curly braces { } in the function body.
let f = val => val; // 等同于 let f = function (val) { return val }; let sum = (num1, num2) => num1 + num2; // 等同于 let sum = function(num1, num2) { return num1 + num2; };
② If the function body of the arrow function has only one line of code, which returns an object, it can be written as follows:
// 用小括號(hào)包裹要返回的對(duì)象,不報(bào)錯(cuò) let getTempItem = id => ({ id: id, name: "Temp" }); // 但絕不能這樣寫(xiě),會(huì)報(bào)錯(cuò)。 // 因?yàn)閷?duì)象的大括號(hào)會(huì)被解釋為函數(shù)體的大括號(hào) let getTempItem = id => { id: id, name: "Temp" };
③ If The function body of the arrow function has only one statement and does not need to return a value (the most common is to call a function). You can add a void
keyword
let fn = () => void doesNotReturn();
in front of this statement. The most common arrow function The purpose of is to simplify the callback function.
// 例子一 // 正常函數(shù)寫(xiě)法 [1,2,3].map(function (x) { return x * x; }); // 箭頭函數(shù)寫(xiě)法 [1,2,3].map(x => x * x); // 例子二 // 正常函數(shù)寫(xiě)法 var result = [2, 5, 1, 4, 3].sort(function (a, b) { return a - b; }); // 箭頭函數(shù)寫(xiě)法 var result = [2, 5, 1, 4, 3].sort((a, b) => a - b);
2. The difference between arrow functions and ordinary functions
##1. The syntax is more concise and clear
As can be seen from the basic syntax examples above, the definition of arrow functions is much simpler, clearer and faster than the definition of ordinary functions.2. The arrow function will not create its own this (Important!! Understand in depth!!)
Let’s first take a look at the arrow function on MDN Explanation of this.
The arrow function does not create its ownThe arrow function does not have its ownthis
, so it does not have its own
this, it will only start from the upper level of its own scope chain Inherit
this.
this, it will capture the # position it is in when
definition (note, when it is defined, not when it is called) ##this of the outer execution environment, and inherit this
this value. Therefore, the pointing of this
in the arrow function is already determined when it is defined, and will never change later. Let’s take a look at an example:
var id = 'Global'; function fun1() { // setTimeout中使用普通函數(shù) setTimeout(function(){ console.log(this.id); }, 2000); } function fun2() { // setTimeout中使用箭頭函數(shù) setTimeout(() => { console.log(this.id); }, 2000) } fun1.call({id: 'Obj'}); // 'Global' fun2.call({id: 'Obj'}); // 'Obj'
In the above example, a normal function is used in
setTimeout in function fun1
. When the function is executed after 2 seconds , at this time the function is actually executed in the global scope, so this
points to the Window
object, and this.id
points to the global variable id
, so the output is 'Global'
.
However, setTimeout
in function fun2
uses an arrow function. The this
of this arrow function is determined when it is defined, and it inherits its outer layer#this
in the execution environment of ##fun2, and when
fun2 is called,
this is changed to the object ## by the
call method #{id: 'Obj'}
, so 'Obj'
is output. Let’s look at another example:
<pre class='brush:php;toolbar:false;'>var id = &#39;GLOBAL&#39;;
var obj = {
id: &#39;OBJ&#39;,
a: function(){
console.log(this.id);
},
b: () => {
console.log(this.id);
}
};
obj.a(); // &#39;OBJ&#39;
obj.b(); // &#39;GLOBAL&#39;</pre>
In the above example, the method
of object
obj is defined using an ordinary function, 3、箭頭函數(shù)繼承而來(lái)的this指向永遠(yuǎn)不變(重要??!深入理解!?。?/strong> 上面的例子,就完全可以說(shuō)明箭頭函數(shù)繼承而來(lái)的 4、.call()/.apply()/.bind()無(wú)法改變箭頭函數(shù)中this的指向 5、箭頭函數(shù)不能作為構(gòu)造函數(shù)使用 我們先了解一下構(gòu)造函數(shù)的new都做了些什么?簡(jiǎn)單來(lái)說(shuō),分為四步:
① JS內(nèi)部首先會(huì)先生成一個(gè)對(duì)象;
② 再把函數(shù)中的this指向該對(duì)象;
③ 然后執(zhí)行構(gòu)造函數(shù)中的語(yǔ)句;
④ 最終返回該對(duì)象實(shí)例。 但是?。∫?yàn)榧^函數(shù)沒(méi)有自己的 6、箭頭函數(shù)沒(méi)有自己的arguments 箭頭函數(shù)沒(méi)有自己的 上面例子二,①②③處的輸出結(jié)果如下: 很明顯,普通函數(shù) 可以在箭頭函數(shù)中使用rest參數(shù)代替arguments對(duì)象,來(lái)訪問(wèn)箭頭函數(shù)的參數(shù)列表?。?/strong> 7、箭頭函數(shù)沒(méi)有原型prototype 8、箭頭函數(shù)不能用作Generator函數(shù),不能使用yeild關(guān)鍵字 【相關(guān)推薦:javascript視頻教程、web前端】 The above is the detailed content of What is the difference between arrow functions and ordinary functions in es6. For more information, please follow other related articles on the PHP Chinese website!ordinary function When called as a method on an object,
this points to the object
to which it belongs. Therefore, this.id is
obj.id, so 'OBJ'
is output.
However, method b
is defined using an arrow function. this
in the arrow function actually inherits this
in the global execution environment where it is defined, so Points to the Window
object, so 'GLOBAL'
is output. (It should be noted here that the curly braces
{} that define the object cannot form a separate execution environment, it is still in the global execution environment!!
)this
指向永遠(yuǎn)不變。對(duì)象obj
的方法b
是使用箭頭函數(shù)定義的,這個(gè)函數(shù)中的this
就永遠(yuǎn)指向它定義時(shí)所處的全局執(zhí)行環(huán)境中的this
,即便這個(gè)函數(shù)是作為對(duì)象obj
的方法調(diào)用,this
依舊指向Window
對(duì)象。.call()
/.apply()
/.bind()
方法可以用來(lái)動(dòng)態(tài)修改函數(shù)執(zhí)行時(shí)this
的指向,但由于箭頭函數(shù)的this
定義時(shí)就已經(jīng)確定且永遠(yuǎn)不會(huì)改變。所以使用這些方法永遠(yuǎn)也改變不了箭頭函數(shù)this
的指向,雖然這么做代碼不會(huì)報(bào)錯(cuò)。var id = 'Global';
// 箭頭函數(shù)定義在全局作用域
let fun1 = () => {
console.log(this.id)
};
fun1(); // 'Global'
// this的指向不會(huì)改變,永遠(yuǎn)指向Window對(duì)象
fun1.call({id: 'Obj'}); // 'Global'
fun1.apply({id: 'Obj'}); // 'Global'
fun1.bind({id: 'Obj'})(); // 'Global'
this
,它的this
其實(shí)是繼承了外層執(zhí)行環(huán)境中的this
,且this
指向永遠(yuǎn)不會(huì)隨在哪里調(diào)用、被誰(shuí)調(diào)用而改變,所以箭頭函數(shù)不能作為構(gòu)造函數(shù)使用,或者說(shuō)構(gòu)造函數(shù)不能定義成箭頭函數(shù),否則用new
調(diào)用時(shí)會(huì)報(bào)錯(cuò)!let Fun = (name, age) => {
this.name = name;
this.age = age;
};
// 報(bào)錯(cuò)
let p = new Fun('cao', 24);
arguments
對(duì)象。在箭頭函數(shù)中訪問(wèn)arguments
實(shí)際上獲得的是外層局部(函數(shù))執(zhí)行環(huán)境中的值。// 例子一
let fun = (val) => {
console.log(val); // 111
// 下面一行會(huì)報(bào)錯(cuò)
// Uncaught ReferenceError: arguments is not defined
// 因?yàn)橥鈱尤汁h(huán)境沒(méi)有arguments對(duì)象
console.log(arguments);
};
fun(111);
// 例子二
function outer(val1, val2) {
let argOut = arguments;
console.log(argOut); // ①
let fun = () => {
let argIn = arguments;
console.log(argIn); // ②
console.log(argOut === argIn); // ③
};
fun();
}
outer(111, 222);
outer
內(nèi)部的箭頭函數(shù)fun
中的arguments
對(duì)象,其實(shí)是沿作用域鏈向上訪問(wèn)的外層outer
函數(shù)的arguments
對(duì)象。let sayHi = () => {
console.log('Hello World !')
};
console.log(sayHi.prototype); // undefined

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
