箭头函数
2018-05-24 本文已影响0人
天涯笑笑生
一、简介
- Arrow Function(箭头函数),ES6标准新增函数
- 相当于匿名函数,简化函数定义,使用
=>
连接参数和函数体 - 无自身
this
- 不可以使用
new
实例化
二、使用
传参
- 无参数,不可省略括号
() => { statements }
- 一个参数,括号可有可无
(singleParam) => { statements }
singleParam => { statements }
- 多个参数,必须放在括号内
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
- 可变参数、默认参数,以及在参数列表中析构
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
// Destructuring within the parameter list is also supported
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6
函数体
- 只有一条表达式,可以省略{ ... }和return
注:但表达式返回一个object时,如果直接返回{foo: bar}
,会和{···}
冲突,所以要使用括号
params => ({foo: bar})
- 包含多条语句,{ ... }不可以省略
map使用
var elements = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
elements.map(function(element ) {
return element.length;
}); // [8, 6, 7, 9]
elements.map(element => {
return element.length;
}); // [8, 6, 7, 9]
elements.map(({ length }) => length); // [8, 6, 7, 9]
this
- 容易出错,谨慎使用
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
var f = () => { 'use strict'; return this; };
f() === window; // or the global object
三、易错
自身无this
'use strict';
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
'use strict';
var obj = {
a: 10
};
Object.defineProperty(obj, 'b', {
get: () => {
console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
}
});
不可以new
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
无prototype
var Foo = () => {};
console.log(Foo.prototype); // undefined
举例
// An empty arrow function returns undefined
let empty = () => {};
(() => 'foobar')();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression
// see 'IIFE' in glossary)
var simple = a => a > 15 ? 15 : a;
simple(16); // 15
simple(10); // 10
let max = (a, b) => a > b ? a : b;
// Easy array filtering, mapping, ...
var arr = [5, 6, 13, 0, 1, 18, 23];
var sum = arr.reduce((a, b) => a + b);
// 66
var even = arr.filter(v => v % 2 == 0);
// [6, 0, 18]
var double = arr.map(v => v * 2);
// [10, 12, 26, 0, 2, 36, 46]
// More concise promise chains
promise.then(a => {
// ...
}).then(b => {
// ...
});
// Parameterless arrow functions that are visually easier to parse
setTimeout( () => {
console.log('I happen sooner');
setTimeout( () => {
// deeper code
console.log('I happen later');
}, 1);
}, 1);