arrow function

The ES6 standard has added a new function: Arrow Function.

Why is it called Arrow Function? Because its definition uses an arrow:

x => x * x

The arrow function above is equivalent to:

function (x) {
    return x * x;
}

Arrow functions are equivalent to anonymous functions and simplify function definitions. There are two forms of arrow functions, one is like the above, which contains only one expression, and even the { ... }sum returnis omitted. There is also one that can contain multiple statements, in which case the { ... }sum cannot be omitted return:

copy code
x => {
    if (x > 0) {
        return x * x;
    }
    else {
        return - x * x;
    }
}
copy code

If the parameter is not one, it needs to be enclosed in parentheses ():

copy code
// Two parameters:
(x, y) => x * x + y * y

// no parameters:
() => 3.14

// variable parameter:
(x, y, ...rest) => {
    var i, sum = x + y;
    for (i=0; i<rest.length; i++) {
        sum += rest[i];
    }
    return sum;
}
copy code

If you want to return an object, you should pay attention to it, if it is a single expression, it will report an error if it is written like this:

// SyntaxError:
x => { foo: x }
因为和函数体的{ ... }有语法冲突,所以要改为:
// ok:
x => ({ foo: x })

this

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

Recalling the previous example, the following example does not give the expected result due to the mishandling of the binding by the JavaScript function :this

copy code
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};
copy code

Now, the fully fixed thispointer of arrow functions thisalways points to the lexical scope, which is the outer caller obj:

copy code
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this points to the obj object
        return fn();
    }
};
obj.getAge(); // 25
copy code

If you use arrow functions, the previous hack is written:

var that = this;

is no longer needed.

Since thisthe arrow function has been bound according to the lexical scope, when using call()or apply()calling the arrow function, it cannot thisbe bound, that is, the first parameter passed in is ignored:

copy code
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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326395329&siteId=291194637