Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between arrow functions and ordinary functions in es6

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the difference between the arrow function and the ordinary function in es6. What is introduced in this article is very detailed and has a certain reference value. Interested friends must read it!

Differences: 1, the definition of the arrow function than ordinary function definition to be concise, much clearer, quickly quick; 2, the arrow function will not create its own this, and ordinary function will; 3, the arrow function can not be used as a constructor, and the arrow function can be used as a constructor; 4, the arrow function does not have its own arguments, and the arrow function has.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

The arrow function is a high-frequency test site in the front-end interview, and the arrow function is ES6's API, which many people know, because its syntax is more concise than the general function, so it is loved by everyone.

1. Basic grammar

Arrow = > is allowed in ES6 to define the arrow function. Let's look at a simple example of the syntax:

/ / Arrow function let fun = (name) = > {/ / function body return `Hello ${name}! `;}; / / equivalent to let fun = function (name) {/ / function body return `Hello ${name}!`;}

As you can see, defining arrowhead functions is much more concise in number 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 parentheses before = >, and the body of the function is followed by curly braces after = >.

About the parameters of the arrow function:

① if the arrow function has no arguments, just write an empty parenthesis.

② if the arrowhead function has only one argument, you can also omit the parentheses of the wrap parameter.

③ if the arrowhead function has multiple arguments, separate the arguments with commas (,) in turn and wrap them in parentheses.

/ / there is no parameter let fun1 = () = > {console.log;}; / / there is only one parameter, and the parentheses let fun2 = name = > {console.log (`val1 ${name}! `)} can be omitted; / / there are multiple parameters 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 sentence of code, which simply returns a variable or a simple JS expression, you can omit the curly braces {} of the function body.

Let f = val = > val;// is equivalent to let f = function (val) {return val}; let sum = (num1, num2) = > num1 + num2;// is equivalent to let sum = function (num1, num2) {return num1 + num2;}

② if the function body of the arrow function has only one sentence of code, it returns an object, which can be written as follows:

/ / wrap the returned object in parentheses and do not report an error let getTempItem = id = > ({id: id, name: "Temp"}); / / but never write this way, it will report an error. / / because the curly braces of the object are interpreted as the curly braces of the function body 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 precede the statement with a void keyword

Let fn = () > void doesNotReturn ()

The most common use of the arrow function is to simplify the callback function.

/ / example 1 / / normal function writing [1mem2mag3] .map (function (x) {return x * x;}); / / Arrowhead function writing [1Zhuo 2mague 3] .map (x = > x * x); / / example 2 / / normal function writing var result = [2,5,1,4,3] .sort (function (a, b) {return a-b;}) / / Arrow function var result = [2,5,1,4,3] .sort ((a, b) = > a-b)

Second, the difference between arrowhead function and ordinary function

1. The grammar is more concise and clear

As you can see from the basic syntax example above, the definition of the arrowhead function is much simpler, clearer, and faster than the ordinary function definition.

2. The arrow function will not create its own this (important! In-depth understanding! )

Let's first take a look at the explanation of the arrow function this on MDN.

The arrow function does not create its own this, so it does not have its own this, it only inherits this from one level above its scope chain.

The arrow function does not have its own this, it captures the this of the outer execution environment in which it is defined (note that it is defined, not called) and inherits this value. Therefore, the direction of the this in the arrow function is determined when it is defined and will never change after that.

Let's look at an example:

Var id = 'Global';function fun1 () {/ / setTimeout using ordinary function setTimeout (function () {console.log (this.id);}, 2000);} function fun2 () {/ / setTimeout using arrow function setTimeout (() = > {console.log (this.id);}, 2000)} fun1.call ({id:' Obj'}) / / 'Global'fun2.call ({id:' Obj'}); / / 'Obj'

In the above example, the ordinary function is used in the setTimeout in the function fun1. When the function executes 2 seconds later, 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 output 'Global'. But the setTimeout in the function fun2 uses the arrow function, the this of this arrow function is determined when it is defined, it inherits the this in the execution environment of its outer fun2, and when fun2 is called, the this is changed to the object {id: 'Obj'} by the call method, so output' Obj'.

Let's look at another example:

Var id = 'GLOBAL';var obj = {id:' OBJ', a: function () {console.log (this.id);}, b: () = > {console.log (this.id);}}; obj.a (); / / 'OBJ'obj.b (); / /' GLOBAL'

In the above example, the method an of the object obj is defined by an ordinary function, and when an ordinary function is called as a method of an object, this points to the object to which it belongs. So, this.id is obj.id, so output 'OBJ'. But method b is defined using the arrow function, and the this in the arrow function actually inherits the this in the global execution environment in which it was defined, so it points to the Window object, so it outputs' GLOBAL'. Note here that the curly braces {} that define the object cannot form a separate execution environment, it is still in the global execution environment! )

3. The this direction inherited from the arrow function will never change (important! In-depth understanding! )

The above example fully illustrates that the this direction inherited from the arrow function will never change. The method b of the object obj is defined using the arrow function, and the this in this function always points to the this in the global execution environment in which it was defined, and even if the function is called as a method call to the object obj, the this still points to the Window object.

4. Call () / .apply () / .bind () cannot change the direction of this in the arrow function

The .call () / .apply () / .bind () method can be used to dynamically modify the direction of the this when the function is executed, but because the this definition of the arrow function is determined and will never change. So using these methods will never change the direction of the arrow function this, although the code will not report an error.

Var id = 'Global';// Arrow function is defined in the global scope let fun1 = () = > {console.log (this.id)}; fun1 (); / /' Global'// this always points to the Window object fun1.call ({id: 'Obj'}); / /' Global'fun1.apply ({id: 'Obj'}) / / 'Global'fun1.bind ({id:' Obj'}) (); / / 'Global'

5. The arrow function cannot be used as a constructor

Let's take a look at what the new of the constructor does. To put it simply, it is divided into four steps: ① JS will first become an object; ② points the this in the function to the object; ③ then executes the statement in the constructor; and ④ finally returns the object instance.

But! Because the arrow function does not have its own this, its this actually inherits the this in the outer execution environment, and the this point never changes with where it is called and by whom, so the arrow function cannot be used as a constructor, or it cannot be defined as an arrow function, otherwise an error will be reported when calling with new!

Let Fun = (name, age) = > {this.name = name; this.age = age;}; / / error let p = new Fun ('cao', 24)

6. The Arrow function does not have its own arguments

The arrow function does not have its own arguments object. Accessing arguments in the arrow function actually gets the value in the outer local (function) execution environment.

/ / example 1: let fun = (val) = > {console.log (val); / / the following line will report an error / / Uncaught ReferenceError: arguments is not defined / / because there is no arguments object console.log (arguments) in the outer global environment;}; fun (111); / / example 2 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)

In example 2 above, the output at ①②③ is as follows:

Obviously, the arguments object in the arrow function fun inside the ordinary function outer is actually the arguments object of the outer outer function accessed up the scope chain.

You can use the rest parameter instead of the arguments object in the arrow function to access the parameter list of the arrow function!

7. The arrow function does not have a prototype prototype.

Let sayHi = () = > {console.log ('Hello World!')}; console.log (sayHi.prototype); / / undefined

8. The arrow function cannot be used as a Generator function, and the yeild keyword cannot be used

These are all the contents of the article "what is the difference between arrow functions and ordinary functions in es6". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report