The ES6 standard has added a new function: Arrow Function.
Why is it called Arrow Function? Because it is defined using an arrow:
x => x * x
The above arrow function is equivalent to:
function (x) { return x * x; }
Before continuing to learn the arrow function, please test whether your browser supports ES6's Arrow Function
Arrow functions are equivalent to anonymous functions and simplifies function definition. There are two formats for arrow functions, one like the one above, which only contains one expression, and even { ... } and return are omitted. There is another type that can contain multiple statements, which cannot be omitted at this time.{ ... }andreturn:
x => { if (x > 0) { return x * x; } else { return - x * x; } }
If the parameters are not one, brackets are required()Included:
// Two parameters:(x, y) => x * x + y * y // No parameters:() => 3.14 // Variable parameters:(x, y, ...rest) => { var i, sum = x + y; for (i=0; i<; i++) { sum += rest[i]; } return sum; }
If you want to return an object, you should note that if it is a single expression, it will report an error if you write it like this:
// SyntaxError: x => { foo: x }
Because of the function body{ ... }There is a syntax conflict, so change it to:
// ok: x => ({ foo: x })
this
Arrow functions seem to be an abbreviation for anonymous functions, but in fact, there is a clear difference between arrow functions and anonymous functions: this inside the arrow functions is lexical scope, determined by the context.
Looking back at the previous example, because JavaScript function pairsthisThe binding error handling, the following example cannot get the expected result:
var obj = { birth: 1990, getAge: function () { var b = ; // 1990 var fn = function () { return new Date().getFullYear() - ; // this points to window or undefined }; return fn(); } };
Now, the arrow function is completely fixedthispointing,thisAlways point to the lexical scope, that is, the outer callerobj:
var obj = { birth: 1990, getAge: function () { var b = ; // 1990 var fn = () => new Date().getFullYear() - ; // this points to the obj object return fn(); } }; (); // 25
If you use the arrow function, the previous hack is written:
var that = this;
No more needed.
becausethisThe arrow function has been bound according to the lexical scope, socall()orapply()When calling the arrow function, this cannot be bound, that is, the first parameter passed in is ignored:
var obj = { birth: 1990, getAge: function (year) { var b = ; // 1990 var fn = (y) => y - ; // Still 1990 return ({birth:2000}, year); } }; (2015); // 25
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.