ES6 arrow function is somehow like CoffeeScirpt.

CoffeeScript:

 //function                     call
coffee = -> coffee()
coffee=(message) -> coffee("Yo"), coffee "Yo"
coffee=(message, other) -> coffee("Yo", 2), coffee "Yo", 2

Now we rewrite a ES5 function to ES6 function:

ES5:

var greeting = function(message, name){
return message + name;
}

ES6:

First thing in ES6, we can remove the function keyword and add => on the right side of the params:

var greeting = (message, name) => {
return message + name ;
}

Second, we can remove 'return' and {};

var greeting = (message, name) => message + name

Example 1:

var f = () => 5;
// 等同于
var f = function (){ return 5 };

Example 2:


//ES6
var msg = message => "Hello Es6"//ES5
var msg = function(message){
return "Hello Es6";
}

Example 3:

// 正常函数写法
[1,2,3].map(function (x) {
return x * x;
}); // 箭头函数写法
[1,2,3].map(x => x * x);

Example 4:

// 正常函数写法
var result = values.sort(function(a, b) {
return a - b;
}); // 箭头函数写法
var result = value.sort((a,b)=> a- b)

=> function helps to sovle the context problem:


//ES5

var deliveryBoy = {
name: "John", receive: function(){
var that = this;
this.handleMessage("Hello", function(message){
//Here we have a very amazing handle function
//which combine the name and message
console.log(message + ' '+that.name);
});
}, handleMessage: function(message, handler){
handler(message);
} } deliveryBoy.receive();

In the code, we see:

console.log(message + ' '+that.name);

We use var that = this; and that.name to refer to "John". It looks quite confusing.

Arrow function helps us out of this:


var deliveryBoy = {
name: "John", receive: function(){this.handleMessage("Hello", message => console.log(message + ' '+this.name));
}, handleMessage: function(message, handler){
handler(message);
} } deliveryBoy.receive();

Inside the code, we still use this.name to refer "John". This is because, => refer to the deliveryBoy object.

箭头函数有几个使用注意点。

  • 函数体内的this对象,绑定定义时所在的对象,而不是使用时所在的对象。
  • 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
  • 不可以使用arguments对象,该对象在函数体内不存在。

最新文章

  1. 学习mongo系列(三) update() save()
  2. Appium移动自动化测试(四)--one demo
  3. Mac上安装node.js
  4. iOS学习笔记---oc语言第一天
  5. iPhone的定位技术与Core Location框架
  6. 2014年acm亚洲区域赛·鞍山站
  7. 新手不得不注意HTML CSS 规范
  8. Ansi,UTF8,Unicode,ASCII编码的差别
  9. U9文件与文件系统的压缩和打包
  10. md5sum校验文件完整性
  11. oracle高效分页查询总结
  12. MATLAB批量读入图片
  13. Java简单知识梳理
  14. Java序列化框架性能比較
  15. Fiddler抓取https设置及其原理
  16. OAuth2.0学习(1-8) 授权方式五之Access_Token令牌过期更新
  17. 【Dp】Bzoj1296 [SCOI2009] 粉刷匠
  18. 《神经网络算法与实现-基于Java语言》的读书笔记
  19. 分享几个有趣的Linux命令
  20. 微信小程序实战[01]

热门文章

  1. 关于在webapi + ef + 视图 + top查询的问题
  2. vue实现简单在线聊天
  3. HDU 6166 Senior Pan (最短路变形)
  4. thinkphp之自动完成
  5. CentOS7编译安装PostgreSQL
  6. utf-8 长度
  7. PHP:根据二维数组中的某个字段进行排序
  8. 【深度搜索+剪枝】POJ1011-Sticks
  9. Node.js的http模块理解
  10. Codeforces Beta Round #3 C. Tic-tac-toe 模拟题