Home Web Front-end Front-end Q&A What is the difference between arrow functions and ordinary functions in es6

What is the difference between arrow functions and ordinary functions in es6

Mar 08, 2022 pm 12:11 PM
javascript es6 arrow function Ordinary function

Difference: 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.

What is the difference between arrow functions and ordinary functions in es6

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:

// 箭头函数
let fun = (name) => {
    // 函数体
    return `Hello ${name} !`;
};

// 等同于
let fun = function (name) {
    // 函数体
    return `Hello ${name} !`;
};
Copy after login

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.

// 没有参数
let fun1 = () => {
    console.log(111);
};

// 只有一个参数,可以省去参数括号
let fun2 = name => {
    console.log(`Hello ${name} !`)
};

// 有多个参数
let fun3 = (val1, val2, val3) => {
    return [val1, val2, val3];
};
Copy after login

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;
};
Copy after login

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

// 用小括号包裹要返回的对象,不报错
let getTempItem = id => ({ id: id, name: "Temp" });

// 但绝不能这样写,会报错。
// 因为对象的大括号会被解释为函数体的大括号
let getTempItem = id => { id: id, name: "Temp" };
Copy after login

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 voidkeyword

let fn = () => void doesNotReturn();
Copy after login

in front of this statement. The most common arrow function The purpose of is to simplify the callback function.

// 例子一
// 正常函数写法
[1,2,3].map(function (x) {
  return x * x;
});

// 箭头函数写法
[1,2,3].map(x => x * x);

// 例子二
// 正常函数写法
var result = [2, 5, 1, 4, 3].sort(function (a, b) {
  return a - b;
});

// 箭头函数写法
var result = [2, 5, 1, 4, 3].sort((a, b) => a - b);
Copy after login

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 own

this, so it does not have its own this, it will only start from the upper level of its own scope chain Inherit this.

The arrow function does not have its own

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中使用普通函数
    setTimeout(function(){
        console.log(this.id);
    }, 2000);
}

function fun2() {
    // setTimeout中使用箭头函数
    setTimeout(() => {
        console.log(this.id);
    }, 2000)
}

fun1.call({id: 'Obj'});     // 'Global'

fun2.call({id: 'Obj'});     // 'Obj'
Copy after login

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: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var id = &amp;#39;GLOBAL&amp;#39;; var obj = { id: &amp;#39;OBJ&amp;#39;, a: function(){ console.log(this.id); }, b: () =&gt; { console.log(this.id); } }; obj.a(); // &amp;#39;OBJ&amp;#39; obj.b(); // &amp;#39;GLOBAL&amp;#39;</pre><div class="contentsignin">Copy after login</div></div>In the above example, the method

a

of object

obj

is defined using an ordinary function, 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!!)

3、箭头函数继承而来的this指向永远不变(重要!!深入理解!!)

上面的例子,就完全可以说明箭头函数继承而来的this指向永远不变。对象obj的方法b是使用箭头函数定义的,这个函数中的this永远指向它定义时所处的全局执行环境中的this,即便这个函数是作为对象obj的方法调用,this依旧指向Window对象。

4、.call()/.apply()/.bind()无法改变箭头函数中this的指向

.call()/.apply()/.bind()方法可以用来动态修改函数执行时this的指向,但由于箭头函数的this定义时就已经确定且永远不会改变。所以使用这些方法永远也改变不了箭头函数this的指向,虽然这么做代码不会报错。

var id = &#39;Global&#39;;
// 箭头函数定义在全局作用域
let fun1 = () => {
    console.log(this.id)
};

fun1();     // &#39;Global&#39;
// this的指向不会改变,永远指向Window对象
fun1.call({id: &#39;Obj&#39;});     // &#39;Global&#39;
fun1.apply({id: &#39;Obj&#39;});    // &#39;Global&#39;
fun1.bind({id: &#39;Obj&#39;})();   // &#39;Global&#39;
Copy after login

5、箭头函数不能作为构造函数使用

我们先了解一下构造函数的new都做了些什么?简单来说,分为四步: ① JS内部首先会先生成一个对象; ② 再把函数中的this指向该对象; ③ 然后执行构造函数中的语句; ④ 最终返回该对象实例。

但是!!因为箭头函数没有自己的this,它的this其实是继承了外层执行环境中的this,且this指向永远不会随在哪里调用、被谁调用而改变,所以箭头函数不能作为构造函数使用,或者说构造函数不能定义成箭头函数,否则用new调用时会报错!

let Fun = (name, age) => {
    this.name = name;
    this.age = age;
};

// 报错
let p = new Fun(&#39;cao&#39;, 24);
Copy after login

6、箭头函数没有自己的arguments

箭头函数没有自己的arguments对象。在箭头函数中访问arguments实际上获得的是外层局部(函数)执行环境中的值。

// 例子一
let fun = (val) => {
    console.log(val);   // 111
    // 下面一行会报错
    // Uncaught ReferenceError: arguments is not defined
    // 因为外层全局环境没有arguments对象
    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);
Copy after login

上面例子二,①②③处的输出结果如下:

What is the difference between arrow functions and ordinary functions in es6

很明显,普通函数outer内部的箭头函数fun中的arguments对象,其实是沿作用域链向上访问的外层outer函数的arguments对象。

可以在箭头函数中使用rest参数代替arguments对象,来访问箭头函数的参数列表!!

7、箭头函数没有原型prototype

let sayHi = () => {
    console.log(&#39;Hello World !&#39;)
};
console.log(sayHi.prototype); // undefined
Copy after login

8、箭头函数不能用作Generator函数,不能使用yeild关键字

【相关推荐: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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles