ES6 arrow function and its scope

Source: Internet
Author: User
Tags foreach constructor event listener split

The original is from my Front-end blog:

http://www.hacke2.cn/arrow-functions-and-their-scope/


http://es6rocks.com/2014/10/arrow-functions-and-their-scope/the original link translation: @liningone Rock ES6 China Station is about to go online, we look forward to it, You can also contact me or ES6 to make a contribution to the event.

In ES6 many great new features, the arrow function (or the big arrow function) is one of the most interesting! It's not just great and cool, it's good to use the scope, fast and easy to use the technology we used before, reducing a lot of code ... But if you don't understand the principle of the arrow function, it might be a little hard to understand. So, let's take a look at the arrow function, that's right now! Execution Environment

You can learn and try it yourself, you can simply copy the sample program code to your browser console. Now, we recommend using Firefox (22+) developer Tools, Firefox (22+) developer tools now support arrow functions, you can also use Google Chrome. If you use Google Chrome, you have to do the following two things:--enter "About:flags" in the Address bar in Google Chrome, and find the "Use experience javascript" option to turn on use. -- Add "use strict" at the beginning of the function and then test the arrow function in your Google browsing (hint: Please google browser v38, I was the browser version of the pit):

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

Fortunately, there will be more and more browsers supporting ES6 features later on. Now that you've done all the preparation, let's go ahead and dive into it! a new topic

Recently, we are discussing a topic about ES6: About arrow functions like this:

=
the new syntax

As the discussion produces a new syntax:

param = Expression

The new syntax is to function on a variable, you can declare multiple variables in an expression, and the following are the usage patterns of the arrow functions:

  one parameter corresponds to an expression
param = = expression;//for example x = x+2;

Multiple parameters correspond to an expression
(param [, param]) = + expression;//For example (x, y) = (× + y);

One parameter corresponds to more than one representation
param = = {statements;}//For example x = > {× x + +; return ×;};  multiple parameters correspond to multiple expressions
([param] [, param]) + = {statements}//(x, y) = {X++;y++;return x*y;};

There is no parameter in the expression
() = expression;//For example var flag = (() = () = 2); flag equals 2

() = {statements;}//For example var flag = ( ) = = {return 1;}) (); Flag equals 1

 //passed in an expression that returns an object
([param]) = ({key:value});
For example  var fuc = (x) = = ({key:x})
        var object = fuc (1);
        Alert (object);//{key:1}
how the arrow functions are implemented

We can convert a normal function into an arrow function to achieve:

The current function
var func = function (param) {    
	return Param.split ("");
}
Use the arrow function to implement
var func = param = Param.split ("");

From the above example, we can see that the syntax of the arrow function is actually returning a new function with the function body and parameters

So we can call the function we just created:

Func ("Felipe Moura"); returns ["Felipe", "Moura"]
Execute function immediately (Iife)

You can use the arrow functions in an immediate execution function, for example:

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

This line of code produces a temporary function that has a parameter x, the return value of the function is x*2, and the system immediately executes the temporary function, assigning 3 to the parameter x.

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

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

Consider the following function:

var func = x =
    + {return x + +;
};

We have listed some common questions:

-The arguments of the temporary function created by the arrow function is what we expected to work

Console.log (arguments);

-typeof and Instanceof functions can also check temporary functions normally

Func instanceof Function; True
typeof func;//function
Func.constructor = = function;//True

-Putting the arrow function in parentheses is not valid

  Valid general Syntax
(function (x, y) {
    x= x * 2;
    return x + y;
} (3, "B"));

Invalid arrow function Syntax
((x, y) + = {
    x= x * 2;
    return x + y;
} (3, "A"));

But it is valid to write this:
((x, y) = {
	x= x * 2;return x + y;
}) (3, "A");//execute function immediately

-Although the arrow function produces a temporary function, this temporary function is not a constructor

var instance= new func (); Typeerror:func is not a constructor

-Also no prototype objects

Func.prototype; Undefined
Scope

The scope of the arrow function and other functions are somewhat different, if not strict mode, the This keyword is pointing to the window, strict mode is undefined, in the constructor of this point is the current object instance, If this is within the function of an object this object is pointed to, this may point to a DOM element, for example, when we add an event listener function, it is possible that this point is not very direct, In fact, this (not just the this variable) variable point is based on a rule to judge: scope flow. Below I will demonstrate this in the event listener function and in the object function inside the case:

In the event listener function:

Document.body.addEventListener (' click ', Function (evt) {
    console.log (this);//The htmlbodyelement itself
});

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"
//Note: This keyword is not explained here, we google,badu it.

In this example, if we let the Person.setname function return the person object itself, we can use this:

Jon.setname ("Jon Doe")
   . GetName ();//"Jon Doe"

In an object:

Let obj = {
    foo: "Bar",
    getit:function () {
        return this.foo;
    }
};

Console.log (Obj.getit ()); "Bar"

However, this also changes when the execution flow (such as using settimeout) and the scope change.

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);
        };

}} Let Mary = new Student ({
    name: "Mary Lou",
    age:13
});

Console.log (Mary.getinfo ()); "Mary Lou,"
mary.sayhi ();
Window

When the settimeout function changes the execution flow, the point of this will become a global object, or it is undefine in strict mode, so we use other variables in the SetTimeout function to point to this object, such as Self,that, Of course, no matter what variables you use, you should first assign to Self,that before settimeout access, or use the Bind method otherwise these variables are undefined.

This is when the arrow function comes up, it can keep the scope, this point will not change.

Let's take a look at the first example above, where 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 () =>{//The only difference are here
            Console.log (this); 
  
   }, (+)
    ;

}} Let Mary = new Student ({
    name: "Mary Lou",
    age:13
});

Console.log (Mary.getinfo ()); "Mary Lou,"
mary.sayhi ();
Object {name: "Mary Lou", Age:13, ...}
  

Analysis: In the Sayhi function, we used the arrow function, the current scope is in a method of the student object, the function of the temporary function generated by the arrow function is the scope of the Sayhi function of the student object. So even if we invoke the temporary function generated by the arrow function in settimeout, this temporary function is also the correct point. interesting and useful to use

Creating a function is easy, and we can take advantage of it to preserve the characteristics of the scope:

For example we can use this: Array.foreach ()

var arr = [' A ', ' e ', ' I ', ' o ', ' u '];
Arr.foreach (vowel = {
    console.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.