search
HomeWeb Front-endJS TutorialUnderstand arrow functions and scope in ES6

Understand arrow functions and scope in ES6

Oct 29, 2020 pm 06:02 PM
es6javascriptarrow function

Understand arrow functions and scope in ES6

Among the many great new features of ES6, the arrow function (or big arrow function) is one of them worth paying attention to! It is not only great and cool, it is good Taking advantage of the scope, we can quickly and easily use the technology we used before, reducing a lot of code... but it may be a bit difficult to understand if you don't understand the principle of arrow functions. So, let's take a look at arrows. Function, now!

Execution Environment

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

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

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

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

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

A new topic

Recently everyone is discussing a topic about ES6: about arrow functions, like this:

=>

New syntax

With the discussion, a new syntax was born:

param => expression

The new syntax is applied to variables. Multiple variables can be declared in expressions. The following is the arrow function Usage mode:

//  一个参数对应一个表达式
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}

How the arrow function is implemented

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

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

From the above example, we can see 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"]

Immediate execution function (IIFE)

You can execute it in the immediate function Use arrow functions, for example:

( x => x * 2 )( 3 ); // 6

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. The system will then execute this temporary function immediately, changing 3 Assign a value to the formal parameter The following function:

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

We have listed some common problems:

The arguments of the temporary function created by the arrow function will not be set:
var func = x => {
    return x++;
};

The typeof

and

instanceof functions

can also check temporary functions normally:

console.log(arguments); // not defined

Putting arrow functions in parentheses is invalid:

func instanceof Function; // true
typeof func; // function
func.constructor == Function; // true

Although arrow functions will Generate a temporary function, but this temporary function is not a constructor:<pre class='brush:php;toolbar:false;'>// 有效的常规语法 (function (x, y){ x= x * 2; return x + y; } (3, "B") ); // 无效的箭头函数语法 ( (x, y) =&gt; { x= x * 2; return x + y; } ( 3, "A" ) ); // 但是可以这样写就是有效的了: ( (x,y) =&gt; { x= x * 2;return x + y; } )( 3,"A" );//立即执行函数</pre>There is also no prototype object:<pre class='brush:php;toolbar:false;'>var instance= new func(); // TypeError: func is not a constructor</pre>

Scope

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

In the event listening function:

func.prototype; // undefined

In the constructor:
document.body.addEventListener(&#39;click&#39;, function(evt){
    console.log(this); // the HTMLBodyElement itself
});
In In this example, if we let the Person.setName function return the Person object itself, we can use it like this:

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吧。

In an object:

jon.setName("Jon Doe")
.getName(); // "Jon Doe"

But when the execution flow (such as using setTimeout ) and the scope change, this will also change.

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

When the setTimeout function changes the execution flow, the point of this will become a global object, or undefine in strict mode, so in the setTimeout function we use other variables to point to this object. , such as self, that, of course no matter what variables you use, you should first assign values ​​to self, that before setTimeout access, or use the bind method, otherwise these variables will be undefined.

This is the time for the arrow function to appear. It can maintain the scope and the point of this will not change.

Let us look at the first example above, here we use the arrow function:

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

Analysis: In the sayHi function, we use the arrow function, and the current scope is In a method of the student object, the scope of the temporary function generated by the arrow function is also the scope of the sayHi function of the student object. So even if we call the temporary function generated by the arrow function in setTimeout, this in this temporary function is also pointed correctly.

有趣和有用的使用

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

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

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

分析:在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" ]

费布拉奇数列

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

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

let arr = ['a', 'e', 'i', 'o', 'u'];
arr.sort( (a, b)=> a < b? 1: -1 );

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

// EventObject, BodyElement
document.body.addEventListener('click', event=>console.log(event, this));

推荐的链接

下面列出了一系列有用的链接,大家可以去看一看

总结

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

相关免费学习推荐:js视频教程

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

The above is the detailed content of Understand arrow functions and scope in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment