Table of Contents
Execution Environment" >Execution Environment
A new topic" >A new topic
New syntax " >New syntax
How the arrow function is implemented
" >How the arrow function is implemented
Immediate execution function (IIFE)" >Immediate execution function (IIFE)
有趣和有用的使用" >有趣和有用的使用
推荐的链接" >推荐的链接
总结" >总结
Home Web Front-end JS Tutorial An in-depth analysis of arrow functions and their scope in ES6

An in-depth analysis of arrow functions and their scope in ES6

Oct 19, 2020 pm 06:02 PM
es6 javascript Scope arrow function

An in-depth analysis of arrow functions and their 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
}());
Copy after login

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:

=>
Copy after login

New syntax

With the discussion, a new syntax was born:

param => expression
Copy after login

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

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(" ");
Copy after login

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"]
Copy after login

Immediate execution function (IIFE)

You can execute it in the immediate function Use arrow 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. 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"
Copy after login

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

The typeof

and

instanceof functions

can also check temporary functions normally:

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

Putting arrow functions in parentheses is invalid:

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

Although arrow functions will Generate a temporary function, but this temporary function is not a constructor:<div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>There is also no prototype object:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var instance= new func(); // TypeError: func is not a constructor</pre><div class="contentsignin">Copy after login</div></div>

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

In the constructor:
document.body.addEventListener(&#39;click&#39;, function(evt){
    console.log(this); // the HTMLBodyElement itself
});
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:

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 an object:

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

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"
Copy after login

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

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);
});
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)=> a < b? 1: -1 );
Copy after login

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

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

推荐的链接

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

总结

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

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

The above is the detailed content of An in-depth analysis of arrow functions and their scope 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)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

C++ Smart Pointers: From Basics to Advanced C++ Smart Pointers: From Basics to Advanced May 09, 2024 pm 09:27 PM

Smart pointers are C++-specific pointers that can automatically release heap memory objects and avoid memory errors. Types include: unique_ptr: exclusive ownership, pointing to a single object. shared_ptr: shared ownership, allowing multiple pointers to manage objects at the same time. weak_ptr: Weak reference, does not increase the reference count and avoid circular references. Usage: Use make_unique, make_shared and make_weak of the std namespace to create smart pointers. Smart pointers automatically release object memory when the scope ends. Advanced usage: You can use custom deleters to control how objects are released. Smart pointers can effectively manage dynamic arrays and prevent memory leaks.

See all articles