Table of Contents
A new topic" >A new topic
New syntax" >New syntax
Arrow function How is it implemented
" >Arrow function How is it implemented
Immediate execution function (IIFE)" >Immediate execution function (IIFE)
Related thoughts" >Related thoughts
Scope" >Scope
有趣和有用的使用" >有趣和有用的使用
总结" >总结
Home Web Front-end Front-end Q&A What does the es6 equal sign arrow mean?

What does the es6 equal sign arrow mean?

Oct 25, 2022 pm 08:43 PM
javascript es6

The equal sign arrow "=>" in es6 refers to the arrow function, which is an abbreviation of a function. The syntax is (parameter)=>{function body};". The syntax of arrow function expression More concise than function expressions, there is no binding of this, super, arguments and new.target, it cannot be called through the new keyword, and the binding of this cannot be changed.

What does the es6 equal sign arrow mean?

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

=> is an arrow function, which is a new function added in the ES6 standard .As the name suggests, arrow functions are a new syntax that uses arrows (=>) to define functions. The syntax of arrow function expressions is more concise than function expressions, but it is slightly different from traditional JavaScript functions, mainly focusing on the following aspects. :

  • There is no binding of this, super, arguments and new.target, and its value is determined by the nearest non-arrow function in the periphery

  • Cannot Called through the new keyword

  • No prototype

  • The binding of this cannot be changed

  • The arguments object is not supported

  • Duplicate named parameters are not supported

  • The point of this in the function body always points to the object in which it is defined, and It will not point to the object that calls it. We know who executes the function in es5 and who it points to.

Execution Environment

You can learn and try it yourself, you can simply copy the sample program code to your browser console. Now, it is recommended to use Firefox(22) developer tools, Firefox(22) development The browser tool now supports arrow functions, and you can also use Google Chrome. If you use Google Chrome, you have to do the following two things:

  • In the address bar in Google Chrome Enter: about:flags, find the "Use experiential JavaScript" option and enable it.

  • Add use strict at the beginning of the function, and then test the arrow in your Google browser Function bar (tip: please use Google Chrome v38, I was fooled by the browser version at the time):

(function(){
    "use strict";
    // use arrow functions here
}());
Copy after login

Fortunately, more and more browsers will support it in the future. ES6 features. Now that you have completed all the preparations, let’s continue to dive into it!

A new topic

People are discussing recently about A topic in ES6: About arrow functions, like this:

=>
Copy after login

New syntax

With the discussion, a new syntax was born:

param => expression
Copy after login

The new syntax is used on variables. Multiple variables can be declared in expressions. The following is the usage pattern of arrow functions:

//  一个参数对应一个表达式
param => expression;// 例如 x => x+2;

// 多个参数对应一个表达式
(param [, param]) => expression; //例如 (x,y) => (x + y);

// 一个参数对应多个表示式
param => {statements;} //例如 x = > { x++; return x;};

//  多个参数对应多个表达式
([param] [, param]) => {statements} // 例如 (x,y) => { x++;y++;return x*y;};

//表达式里没有参数
() => expression; //例如var flag = (() => 2)(); flag等于2
() => {statements;} //例如 var flag = (() => {return 1;})(); flag就等于1

//传入一个表达式,返回一个对象
([param]) => ({ key: value });
//例如  var fuc = (x) => ({key:x})
        var object = fuc(1);
        alert(object);//{key:1}
Copy after login

Arrow function How is it implemented

We can convert an ordinary function into an arrow function to implement it:

// 当前函数
var func = function (param) {
    return param.split(" ");
}
// 利用箭头函数实现
var func = param => param.split(" ");
Copy after login

From the above example we can It can be seen that the syntax of the arrow function actually returns a new function, which has a function body and parameters.

Therefore, we can call the function we just created like this:

func("Felipe Moura"); // returns ["Felipe", "Moura"]
Copy after login

Immediate execution function (IIFE)

You Arrow functions can be used in immediate execution functions, for example:

( x => x * 2 )( 3 ); // 6
Copy after login

This line of code generates a temporary function. This function has a formal parameter x, and the return value of the function is x*2, and the system will execute it immediately. This temporary function assigns 3 to the formal parameter x.

The following example describes the situation where there are multiple lines of code in the temporary function body:

( (x, y) => {
    x = x * 2;
    return x + y;
})( 3, "A" ); // "6A"
Copy after login

Consider the following function:

var func = x => {
    return x++;
};
Copy after login

We have listed some common problems:

The arrow function creates a temporary function whose arguments will not be Settings:

console.log(arguments); // not defined
Copy after login

typeof and instanceof function can also check temporary functions normally:

func instanceof Function; // true
typeof func; // function
func.constructor == Function; // true
Copy after login

Placing arrow functions within brackets is invalid :

//  有效的常规语法
(function (x, y){
    x= x * 2;
    return x + y;
} (3, "B") );
// 无效的箭头函数语法
( (x, y) => {
    x= x * 2;
    return x + y;
} ( 3, "A" ) );
// 但是可以这样写就是有效的了:
( (x,y) => {
    x= x * 2;return x + y;
} )( 3,"A" );//立即执行函数
Copy after login

Although the arrow function will generate a temporary function, this temporary function is not a constructor:

var instance= new func(); // TypeError: func is not a constructor
Copy after login

There is also no prototype object:

func.prototype; // undefined
Copy after login

Scope

The scope of this arrow function is somewhat different from other functions. If it is not in strict mode, the this keyword points to window, and in strict mode it is undefined, in the constructor This points to the current object instance. If this is within a function of an object, this points to the object. This may point to a DOM element. For example, when we add an event listening function, this may point to something other than It's very straightforward. In fact, the pointing of this (not just this variable) variables is judged according to a rule: scope flow. Below I will demonstrate how this appears in the event listening function and in the object function:

In the event listening function:

document.body.addEventListener('click', function(evt){
    console.log(this); // the HTMLBodyElement itself
});
Copy after login

In the constructor:

function Person () {
    let fullName = null;
    this.getName = function () {
        return fullName;
    };
    this.setName = function (name) {
        fullName = name;
        return this;
    };
}
let jon = new Person();
jon.setName("Jon Doe");
console.log(jon.getName()); // "Jon Doe"
//注:this关键字这里就不解释了,大家自己google,baidu吧。
Copy after login

In In this example, if we let the Person.setName function return the Person object itself, we can use it like this:

jon.setName("Jon Doe")
.getName(); // "Jon Doe"
Copy after login

In an object:

let obj = {
    foo: "bar",
    getIt: function () {
        return this.foo;
    }
};
console.log( obj.getIt() ); // "bar"
Copy after login

但是当执行流(比如使用了setTimeout)和作用域变了的时候,this也会变。

function Student(data){
    this.name = data.name || "Jon Doe";
    this.age = data.age>=0 ? data.age : -1;
    this.getInfo = function () {
        return this.name + ", " + this.age;
    };
    this.sayHi = function () {
        window.setTimeout( function () {
            console.log( this );
        }, 100 );
    }
}

let mary = new Student({
    name: "Mary Lou",
    age: 13
});
console.log( mary.getInfo() ); // "Mary Lou, 13"
mary.sayHi();
// window
Copy after login

当setTimeout函数改变了执行流的情况时,this的指向会变成全局对象,或者是在严格模式下就是undefine,这样在setTimeout函数里面我们使用其他的变量去指向this对象,比如self,that,当然不管你用什么变量,你首先应该在setTimeout访问之前,给self,that赋值,或者使用bind方法不然这些变量就是undefined。

这是后就是箭头函数登场的时候了,它可以保持作用域,this的指向就不会变了。

让我们看下上文起先的例子,在这里我们使用箭头函数:

function Student(data){
    this.name = data.name || "Jon Doe";
    this.age = data.age>=0 ? data.age : -1;
    this.getInfo = function () {
        return this.name + ", " + this.age;
    };
    this.sayHi = function () {
        window.setTimeout( ()=>{
            // the only difference is here
            console.log( this );
        }, 100 );
    }
}

let mary = new Student({
    name: "Mary Lou",
    age: 13
});
console.log( mary.getInfo() ); // "Mary Lou, 13"
mary.sayHi();
// Object { name: "Mary Lou", age: 13, ... }
Copy after login

分析:在sayHi函数中,我们使用了箭头函数,当前作用域是在student对象的一个方法中,箭头函数生成的临时函数的作用域也就是student对象的sayHi函数的作用域。所以即使我们在setTimeout调用了箭头函数生成的临时函数,这个临时函数中的this也是正确的指向。

有趣和有用的使用

创建一个函数很容易,我们可以利用它可以保持作用域的特征:

例如我们可以这么使用:Array.forEach()

var arr = ['a', 'e', 'i', 'o', 'u'];
arr.forEach(vowel => {
    console.log(vowel);
});
Copy after login

分析:在forEach里箭头函数会创建并返回一个临时函数 tempFun,这个tempFun你可以想象成这样的:function(vowel){ console.log(vowel);}但是Array.forEach函数会怎么去处理传入的tempFunc呢?在forEach函数里会这样调用它:tempFunc.call(this,value);所有我们看到函数的正确执行效果。

//在Array.map里使用箭头函数,这里我就不分析函数执行过程了。。。。

var arr = ['a', 'e', 'i', 'o', 'u'];
arr.map(vowel => {
    return vowel.toUpperCase();
});
// [ "A", "E", "I", "O", "U" ]
Copy after login

费布拉奇数列

var factorial = (n) => {
    if(n==0) {
        return 1;
    }
    return (n * factorial (n-1) );
}
factorial(6); // 720
Copy after login

我们也可以用在Array.sort方法里:

let arr = ['a', 'e', 'i', 'o', 'u'];
arr.sort( (a, b)=&gt; a < b? 1: -1 );
Copy after login

也可以在事件监听函数里使用:

// EventObject, BodyElement
document.body.addEventListener('click', event=&gt;console.log(event, this));
Copy after login

总结

尽管大家可能会认为使用箭头函数会降低你代码的可读性,但是由于它对作用域的特殊处理,它能让我们能很好的处理this的指向问题。箭头函数加上let关键字的使用,将会让我们JavaScript代码上一个层次!尽量多使用箭头函数,你可以再你的浏览器测试你写的箭头函数代码,大家可以再评论区留下你对箭头函数的想法和使用方案!我希望大家能享受这篇文章,就像你会不就的将来享受箭头函数带给你的快乐.

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of What does the es6 equal sign arrow mean?. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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

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

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

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