Description: The arrow function is one of the new features of ES6, which provides a new syntax for the writing function for the JS language.
' Use strcit '= [n/a]; // ES5Let es5 = Arr.map (function(n) { return n*2;}); // ES6Let es6 = Arr.map (n = n*2); Console.log (ES5); // [2,4,6]console.log (ES6); // [2,4,6]
The arrow function simplifies the original function syntax, does not need to write functions, if the function body has only one line of code, not even return to write, this feature is keen to simplify the process and work of programmers have a considerable appetite.
The arrow function supports two modes of function body notation, let's call him concise function body and block-level function body.
' Use strcit '; // Concise function Body let fn = x = x * x; // block-level function body let FN = (x, y) = = {return x + y;};
Introduction The function body defaults to return the result of the expression, and the block-level function body needs to return manually. If you want to return an object and want to use a concise function body, you need to write this:
' Use strcit '= () = ( {}); FN (); // {}
If you write var fn = () = {}, then execute FN () only returns undefined.
' Use strict ';//First KindLet person =function(){ This. Age = 2; let that= This; SetTimeout (function() {that.age++; Console.log (That.age); },1000);};//The second KindLet person =function(){ This. Age = 2; SetTimeout (function() { This. age++; Console.log ( This. Age); }.bind (this),1000);};NewPerson ();
Before we wanted to manipulate the settimeout parameter function inside the this might look good with either of these two methods, but now with the arrow function is different, the code is as follows:
' Use strict 'function() { this. Age = 2; = = { this. age++; Console.log (the. age); }; New Person ();
Because the arrow function has already bound the value of this, even using apply or call can not only play the role of parameters, and can not forcibly change the arrow function in this.
' Use strict '; let obj={x:1, Show1:function(y) {let fn= y = = y+ This. x; returnfn (y); }, Show2:function(y) {let fn= v + V + This. x; Let whatever={x:2 }; returnFn.call (whatever, y); }};console.log (Obj.show1 (1));//2Console.log (Obj.show2 (2));//3
The arrow function cannot be used with the New keyword and will error
' Use strict '= () + = { this. A=1new Fn (); // Error
The arrow function about ES6 is used with the internal this point