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 return
is omitted. There is also one that can contain multiple statements, in which case the { ... }
sum cannot be omitted return
:
x => { if (x > 0) { return x * x; } else { return - x * x; } }
If the parameter is not one, it needs to be enclosed in parentheses ()
:
// 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; }
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 this
lexical 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
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(); } };
Now, the fully fixed this
pointer of arrow functions this
always points to the lexical scope, which is the outer caller obj
:
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
If you use arrow functions, the previous hack is written:
var that = this;
is no longer needed.
Since this
the arrow function has been bound according to the lexical scope, when using call()
or apply()
calling the arrow function, it cannot this
be bound, that is, 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