Arrow functions
The ES6 standard adds a new function: arrow function.
x => x * x
相当于:
function (x) { return x * x;}
箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }
和return
都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }
和return
:
x => { if (x > 0) { return x * x; } else { return - x * x; }}
If the arguments are not one, you need to ()
enclose them in parentheses:
// 两个参数:(x, y) => x * x + y * y// 无参数:() => 3.14// 可变参数:(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:
// ok:x => ({ foo: x })
This
The arrow function appears to be a shorthand for anonymous functions, but in fact, there is an obvious difference between an arrow function and an anonymous function: The lexical scope inside the arrow function this
is determined by the context.
Looking back at the previous example, this
The following example does not get the expected result due to the JavaScript function's error handling of the binding:
var obj = {birth: 1990 function () { var b = this . Birth; // 1990 var fn = function () { return new Date (). getFullYear ()-this . Birth; // This points to window or undefined }; return FN (); }};
Now, the arrow function completely fixes this
the point, this
always pointing to the lexical scope, that is, the outer caller obj
:
var obj = { 1990, function () { varthis // 1990 varnewthis// This points to the Obj object return fn ( ); // -
Because the this
lexical scope has been bound in the arrow function, it is call()
apply()
not possible to bind when using or invoking an arrow function, that is, this
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
JS Arrow function