1024programmer JavaScript The difference between arrow function and ordinary function

The difference between arrow function and ordinary function

Preface


The arrow function is a high-frequency test point in the front-end interview link. The arrow function is the API of ES6. I believe many people know it, because its grammar is more than the general The function of is more concise, so it is deeply loved by everyone. This is the API we have been using in our daily development, but most students don’t understand it enough. Let’s learn more about the basic syntax of down arrow functions and the difference between arrow functions and ordinary functions.

1. Basic Grammar

【1.1】Defining Functions

Defining Arrow Functions in Number Grammar It is much more concise than ordinary functions. In ES6, arrows are allowed to be used

=>

to define arrow functions. Arrow functions omit the function keyword, and the parameters of the function are placed in = In the parentheses before the >, the function body follows the curly braces after the =>.

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

 // normal function
 let fun = function (name) {
     return `Hello ${name} !`;
 };

【1.2】Arrow function parameters

① If the arrow function has no parameters, just write an empty parenthesis.

② If the arrow function has only one parameter, the parentheses surrounding the parameter can also be omitted.

③ If the arrow function has multiple parameters, separate the parameters with commas (,) and wrap them in parentheses.

// no parameters
 let fun1 = () => {
     console.log('dingFY');
 };

 // There is only one parameter, you can omit the parameter brackets
 let fun2 = name => {
     console.log(`Hello ${name} !`)
 };

 // There are multiple parameters, separated by commas
 let fun3 = (val1, val2, val3) => {
     return [val1, val2, val3];
 };

【1.3】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, The braces { } around the function body can be omitted.

let fun = val => val;
 // Equivalent to
 let fun = function (val) { return val };

 let sum = (num1, num2) => num1 + num2;
 // Equivalent to
 let sum = function(num1, num2) {
   return num1 + num2;
 };

② If the function body of the arrow function has only one line of code, which is to return an object, it can be written as follows:

/  / Wrap the object to be returned in parentheses without reporting an error
 let getTempItem = id => ({ id: id, name: "Temp" });

 // But it must not be written like this, and an error will be reported, because the curly braces of the object will be 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 Add a void keyword in front of this statement

let fun = () => void doesNotReturn();

Second, the difference between arrow functions and ordinary functions


【2.1】The grammar is more Concise and clear

As can be seen from the basic syntax example of the arrow function above, the definition of the arrow function is much more concise, clear and fast than the definition of the ordinary function.

【2.2】The arrow function has no prototype (prototype), so the arrow function itself does not have this

// arrow function
 let a = () => {};
 console.log(a.prototype); // undefined

 // normal function
 function a() {};
 console.log(a.prototype); // {constructor:f}

【2.3】The arrow function will not create its own this

Arrow function Without its own this, the this of the arrow function points to the this inherited from the first ordinary function in the outer layer when it is defined (note: when it is defined, not when it is called). Therefore, the pointing of this in the arrow function is determined when it is defined, and it will never change afterwards.

let obj = {
   a: 10,
   b: () => {
     console.log(this.a); // undefined
     console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
   },
   c: function() {
     console.log(this.a); // 10
     console.log(this); // {a: 10, b: ƒ, c: ƒ}
   }
 }
 obj.b();
 obj.c();

【2.4】call | apply | bind cannot change the direction of this in the arrow function

call | apply | bind method can It is used to dynamically modify the direction of this when the function is executed, but because the this of the arrow function has been defined and will never change. So using these methods can never change the direction of the arrow function this.

var id = 10;
 let fun = () => {
     console.log(this.id)
 };
 fun(); // 10
 fun. call({ id: 20 }); // 10
 fun.apply({ id: 20 }); // 10
 fun.bind({ id: 20 })(); // 10

【2.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 this when the function is executed, but since the this of the arrow function has been defined when it is defined, it will never change. So using these methods can never change the direction of the arrow function this.

var id = 10;
 let fun = () => {
     console.log(this.id)
 };
 fun(); // 10
 fun. call({ id: 20 }); // 10
 fun.apply({ id: 20 }); // 10
 fun.bind({ id: 20 })(); // 10

【2.5】Arrow functions cannot be used as constructors

Let’s understand first What does the new of the constructor do? To put it simply, it is divided into four steps: ① First, an object will be generated inside JS; ② Then point this in the function to the object; ③ Then execute the statement in the constructor; ④ Finally return 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 point of this will never change with where it is called or by whom it is called, so the arrow function cannot be used as a constructor, or It is said that the constructor 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('dingFY', 24);

【2.6】The arrow function does not bind arguments, and instead uses rest parameters… instead of the arguments object, to Accessing an Arrow Function’s Argument List

Arrow functions do not have their own arguments object. Accessing arguments in an arrow function actually gets the value in the outer local (function) execution environment.

// ordinary function
 function A(a){
   console. log(arguments);
 }
 A(1,2,3,4,5,8); // [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ]

 // arrow function
 let B = (b)=>{
   console. log(arguments);
 }
 B(2,92,32,32); // Uncaught ReferenceError: arguments is not defined

 // rest parameters...
 let C = (...c) => {
   console. log(c);
 }
 C(3,82,32,11323); // [3, 82, 32, 11323]

【2.7】Arrow functions cannot be used as Generator functions, and the yield keyword cannot be used

Recommended tutorial: “JS Tutorial”

The above is the detailed content of the difference between arrow functions and ordinary functions. For more information, please pay attention to other related articles on 1024programmer.com!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/the-difference-between-arrow-function-and-ordinary-function/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索