JS Arrow function

Source: Internet
Author: User

Arrow functions

The ES6 standard adds a new function: arrow function.

x => x * x
相当于:
function (x) {    return x * x;}
箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }return
x => {    if (x > 0) {        return x * x;    }    else {        return - x * x; }}
If the arguments are not one, you need to () enclose them in parentheses:
// 两个参数:(x, y) => x * x + y * y// 无参数:() => 3.14// 可变参数:(x, y, ...rest) => {    var i, sum = x + y; for (i=0; i<rest.length; i++) { sum += rest[i]; } return sum;}

If you want to return an object:
// ok:x => ({ foo: x })

This

The arrow function appears to be a shorthand for anonymous functions, but in fact, there is an obvious difference between an arrow function and an anonymous function: The lexical scope inside the arrow function this is determined by the context.

Looking back at the previous example, this The following example does not get the expected result due to the JavaScript function's error handling of the binding:

 var  obj = {birth:  1990 function   () {  var  b = this . Birth; //  1990  var  fn = function   () { return  new  Date (). getFullYear ()-this . Birth; //  This points to window or undefined         };     return   FN (); }};

Now, the arrow function completely fixes this the point, this always pointing to the lexical scope, that is, the outer caller obj :

var obj = {    1990,    function  () {        varthis  //  1990        varnewthis//  This points to the Obj object        return  fn (    ); //  -

Because the this lexical scope has been bound in the arrow function, it is call() apply() not possible to bind when using or invoking an arrow function, that is, this the first parameter passed in is ignored:

var obj = {    birth: 1990,    getAge: function (year) { var b = this.birth; // 1990 var fn = (y) => y - this.birth; // this.birth仍是1990 return fn.call({birth:2000}, year); }};obj.getAge(2015); // 25
 

JS Arrow function

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.