ES6 allows you to define functions using the arrow (= =)
var f = a = > a// equals varfunction(a) { return A; }
If the arrow function does not require arguments or requires more than one argument, a parenthesis is used to represent the parameter part.
// Invisible Ginseng var f = () = 2; // equivalent to var function return 2 }; // Multiple Formal parameters var sum = (A, b) = + A + B; // equivalent to var function (A, b) { return a + b;};
Use the arrow function to note the point:
The arrow functions have several points of note to use.
(1) The object in the body of the function is the object this
that is defined, not the object in which it is used.
var name = ' Zhang San '; var person = { name:' John Doe ', age : fav:function() { Console.log (this); Console.log (this. name); // John Doe } }person.fav (); // at this point this is the object that uses it, that is, the person object
var person2 = { ' john Doe ', += = {// The current this points to the object (window) Console.log (this) where the definition is located ;} }; Person2.fav (); // Use the arrow function, which represents the object window where the definition is located.
Monomer mode:
var person = { ' pony brother ', fav () { Console.log (this). name); // Brother Pony }}person.fav ();
(2) An object cannot be used arguments
, and the object does not exist in the function body. If you want to use it, you can use the rest parameter instead.
varP1 ={name:' Zhang San ', Age:18, Fav:function() {Console.log (arguments)}} p1.fav (' Girls ', ' The girls '//Arguments (2) ["Girls", "the Sister", callee:?, Symbol (Symbol.iterator):?]// ******************************************************* varP2 ={name:' Zhang San ', Age:18, Fav: ()={console.log (arguments)}} p2.fav (' Girls ', ' The girls '//uncaught referenceerror:arguments is not defined
JS in the arrow function and for the arrow function this point to the problem of the monomer mode