[ES6 series -02] Arrow Function: Whats this? (Arrows and this function and its other)

[Original] code road workers

Hello everyone, here is the code the road workers have the power, I am yards road worker, you are the power.


If not used CSharp of lambdaexpression, nor understand too ES6, that first saw this code is what it feels like?

/* eg.0
 * function definition
 */
 
var arr = [1,2,3,5,8,13,21]

arr.forEach(n => console.log(n))

An array of forEachmethods need to pass in a function (not used in the commission delegate CSharp may seem strange, js parameter was able to be in a way, in fact, there is already some C #), which n =>is what the hell?

This is to say today's protagonist, arrow functions Arrow Function.

#Note:

  • C # various sets of operations a lambda expression is actually a brief anonymous function,
  • ES6 arrows can be understood as a function in C # lambda expression type thing,
  • There is also a Python lambda expression in the (at that time used when there is limited, can only write one),
  • Just different wording between different languages ​​or syntax, so I have a point of view is this:
  • Seriously learn a language, not only stay in the entry, we can not say them to meet the advanced proficient,
  • Others go to school, you will find the programming language is the same, more programming ideas are interlinked
  • I do not work code of Java, C # but will look from Java code is not very strenuous, because really like
    => Java where there are lambda.

The basic usage 1. Arrow Function

1.1 is essentially an anonymous function

  General definition of a function, use the functionkeyword, regardless of the existence of the phenomenon to enhance function foo() { }or define a variable var foo = function() { }in order to find the function call when this is the case, just as everyone has the same name.
  Anonymous function is not the same, it has no name, it can only be invoked in the definition of its position (so say rigorous, but does not affect the understanding of the specific see below). So, with the arrow function to define a single function call it does not, does not make sense. Of course, so I can write, js itself does not complain.
  In addition to the definition of the difference between the time when the use of anonymous functions, with the normal function or similar, or to define a variable, either directly as a callback function written in the parameter position.
  Because there is no per se functionkeywords and method names, so it can not define a class / constructor like ES5 years. There is no reason this can not be used. If " var Foo = () => { }" write, not as a class / constructor, " new Foo()" when error. After all, in the words of ES6 it will not define this class. (By classnow constructor)

/* eg.1
 * function definition
 */
 
//-------------------------------------------------

function logParam(param) {
    console.log(param)
}

logParam("foo")     // foo

//-------------------------------------------------

// Should not define a funtion using arrow-function itself
// because no function name to call and will not execute
(param) => console.log(param)

const foo = (param) => console.log(param)
foo("bar")       // bar

//-------------------------------------------------

1.2 Basic Use Features

  • Ordinary normal writing

    /* eg.2
    * arrow function
    */
    
    //-------------------------------------------------
    var arr = [1,2,3,5,8,13,21]
    
    // Normal:
    console.log(arr.map(function(item, index) {
        return `No.${index}: ${item}`
    }))
    //["No.0: 1", "No.1: 2", "No.2: 3", "No.3: 5", "No.4: 8", "No.5: 13", "No.6: 21"]
    
    // Use arrow function:
    console.log(arr.map((item, index) => {
        return `No.${index}: ${item}`
    }))
    //["No.0: 1", "No.1: 2", "No.2: 3", "No.3: 5", "No.4: 8", "No.5: 13", "No.6: 21"]
    //-------------------------------------------------

    The most intuitive thing is a little easy on the wording of a Diudiu. It is a basic feature is simple, read on.

  • Only one parameter, the parameter parentheses may be omitted

    /* eg.2
    * arrow function
    */
    
    //-------------------------------------------------
    var arr = [1,2,3,5,8,13,21]
    
    // Normal:
    arr.forEach(function(item) {
        console.log("当前元素:" + item)
    })
    
    // Use arrow function:
    arr.forEach( item => {
        console.log("当前元素:" + item)
    })
    //-------------------------------------------------

    The above example is only one itemparameter, the parameter is omitted brackets can be executed normally.

  • Only a method thereof {return expression} , the braces with the return may be omitted

    Of course, if you did not do itself returnalso you can just omit the curly brackets, the default when no return value is the return process undefined.

    /* eg.3
    * arrow function
    */
    //-------------------------------------------------
    
    var arr = [1,2,3,5,8,13,21]
    
    // Normal:
    arr.forEach(function(item){
        console.log("当前元素:" + item)
    })
    console.log(arr.map(function(item,index){
        return `No.${index}: ${item}`
    }))
    
    // Use arrow function:
    arr.foreach((item,index) => console.log(`No.${index}: ${item}`))
    console.log(arr.map((item,index) => `No.${index}: ${item}` ))
    
    //-------------------------------------------------

    The above examples demonstrate, respectively, no returnand there is returnan arrow in the function of simple writing.
    You can view the results in the console under the chrome browser (F12 Open developer mode).

1.3 Supplementary: no parameters

  No argument, is there, you can function like an ordinary, empty parentheses on it. In addition, there is a convention of writing: _. as follows:

/* eg.4
* arrow function: no-param
*/

//-------------------------------------------------
const foo = () => "bar"
const foo = _ => "bar"

// as same as ↓
const foo = function () {
    return "bar"
}

2. Other Features

2.1 thispoints to problems

  Arrow function it feels a lot of light, but there are many problems. Mainly, probably the most frequently encountered is thispointing to the problem.

/* eg.5
* arrow function: this
*/
//-------------------------------------------------

const person = {
    name: "Coder Power",
    greet1: function() {
        console.log(this)
        console.log("Hello!I am " + this.name + ".")
    },
    greet2: () => {
        console.log(this)
        console.log("Hello!I am " + this.name + ".")
    }
}

// 'this' in normal function
// is object person
person.greet1()

// 'this' in arrow function
// is object window
person.greet2()

//-------------------------------------------------

  The above code example, greet1the thispoint of personthe object. It is very easy to understand, except in this js who is calling, who is pointing.

  And greet2in thisit points to the windowobject. How could this be?

  In fact, labor code beginning did not understand, just know that this is not the same. Later careful thought, this arrow in the function when the function is defined in its external functions of this, when it in person definition, at this time this is the window. (Window.person)

  • Arrow function thissummary
    => function does not own this
    => function where thisis the parent scope Lane this
    => can not function apply/ callway of bindingthis

    /* eg.6
    * arrow function: this
    */
    //-------------------------------------------------
    
    // can not change 'this' in arrow function
    // by apply/call
    person.greet2.call(person)
    person.greet2.apply(person)
    // ↑"this.name" will still be undefined
    //-------------------------------------------------

    So we need to use the thismethod to be careful.

Other features arrow 2.2 ES6 function

  1.1 previous paper we say, the function variables arrow out function definition can not newinstantiate an object.
It has nothing to do with inheritance, constructors can not do, there is no prototype ( prototype). Obtaining parameters is limited and method calls pass parameters, can not be used argumentsto take.

ES6 following properties arrow no function / object:

  • Arrow can not functionnew
  • Arrow did not functionprototype

  • Arrow did not functionsuper

    Previous ES5 and ES6 are described in classes and inheritance, which ES6 constructor in the subclass must call in once superthat is the parent class constructor, only generated instance of an object this. The arrow is not a function superof.

  • Arrow did not functionarguments
  • Arrow function is not new.target(already not new, even less new.target a)

    These relatively commonly in use, said arrow or less relevant function, the arrow is intended to simplify the writing function, is used in the more common fill a callback function.


Read here for JavaScript / ES6 in use arrow function Arrow Function of almost mastered it.
Think about what the next scene suitable / not suitable for use arrow function? Comments area can leave a message before you go ah ~

I hope you can help, next goodbye.


Welcome attention to sharing, learning together to improve it.
QRCode / subscription number micro-channel two-dimensional code

QRCode


Guess you like

Origin www.cnblogs.com/CoderMonkie/p/arrow-function-in-es6.html