文章目录
  1. 1. 箭头函数
  2. 2. 例子
  3. 3. 05/18/2016更新

箭头函数

函数式编程~
简写的函数表达式

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var a1 = [
'ab',
'cde',
'fghi'
];

var a2 = a1.map(function(arr){
return arr.length;
})

var a3 = a1.map( arr => arr.length );

console.log(a2+'\n'+a3);
// 2,3,4 \n 2,3,4

在学习nodejs中看到这么一段代码,想了一下=>就代表了一个匿名函数啊,多简洁!
代码示例:

1
2
3
4
5
6
7
http.get('http://www.google.com/index.html', (res) => {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});

05/18/2016更新

There are some different in this key word.

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const EventEmitter = require('events');
    class MyEmitter extends EventEmitter {}
    const myEmitter = new MyEmitter();
    myEmitter.on('event', function(a, b) {
    console.log(a, b, this);
    // Prints:
    // a b MyEmitter {
    // domain: null,
    // _events: { event: [Function] },
    // _eventsCount: 1,
    // _maxListeners: undefined }
    });
    myEmitter.emit('event', 'a', 'b');
1
2
3
4
5
6
7
8
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');

in Instance2 this->{}

文章目录
  1. 1. 箭头函数
  2. 2. 例子
  3. 3. 05/18/2016更新