The difference between an arrow function and a normal function

Source: Internet
Author: User
Tags addall bind

The interview was asked the difference between the arrow function and the normal function ...

-_-||

Borrow a chestnut from someone else:

function make () {
  return () =>{
    console.log (this);
  }
}
var TestFunc = Make.call ({name: ' foo '});
TestFunc (); 
Object {name: ' foo '}
object {name: ' foo '}
You can see the arrow function is defined, this will not change, no matter what way to call it, this will not change;

Cause: The arrow function does not automatically bind local variables, such as This,arguments,super (ES6), New.target (ES6), etc.

So the arrow function does not have its own this value, and the this value within the arrow function inherits from the perimeter scope. When you call this in an arrow function, simply look up the scope chain and find the nearest one to use

{
      ...
      Addall:function AddAll (Pieces) {
        var = this;
        _.each (pieces, function (piece) {
          self.add (piece);
        });}
      ,
      ...
    }

Here, you want to write This.add (piece) in the inner layer function, unfortunately, the inner function does not inherit the value of this from the outer function. In the inner function, this is either window or undefined, and the temporary variable self is used to import the external this value into the intrinsic function. (Another way is to execute. Bind (this) on an internal function, both of which are not very attractive.) At this point, you can use the arrow function to achieve the required


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.