【ES6】之 Arrow Function箭头函数
2016-03-29 18:21
836 查看
基本语法
1. 更简洁的代码,摆脱function
[1, 2, 3].map(function(x) { return x * 2});
es6:
[1, 2, 3].map(x => x * 2);
2.语义化的this
在es6之前,函数都定义了自己的this值,这样会带来一些混乱
//在strict mode下
var self = this;
asyncFunction(function () {
//callback
self.doSomething();
})
如果在es6下就不会有这个问题了,大大简化了我们回调的时候的代码:
asyncFunction(() => this.doSomething());
基本语法
1. (param1, param2, ..., paramN) => { statement }
例:
(x) => { console.log(x); }
2. (param1, param2, ..., paramN) => expression
等价于 (param1, param2, ..., paramN) => { return expression; }
例:
let sum = (x, y) => x + y;
sum(1, 2)
返回值为3
3. 当只有一个参数时,括号可以省略
(param) => { statement }
等价于 param => { statement }
例:
let double = x => x * 2;
double(3)
返回值为6
4. 当没有参数时,需要带上括号
() => { statement }
说明
expression & statement
expression: expression evaluate to a value
statement: statement do something
参考资料
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/
strict mode VS non-strict mode
1. 更简洁的代码,摆脱function
[1, 2, 3].map(function(x) { return x * 2});
es6:
[1, 2, 3].map(x => x * 2);
2.语义化的this
在es6之前,函数都定义了自己的this值,这样会带来一些混乱
//在strict mode下
var self = this;
asyncFunction(function () {
//callback
self.doSomething();
})
如果在es6下就不会有这个问题了,大大简化了我们回调的时候的代码:
asyncFunction(() => this.doSomething());
基本语法
1. (param1, param2, ..., paramN) => { statement }
例:
(x) => { console.log(x); }
2. (param1, param2, ..., paramN) => expression
等价于 (param1, param2, ..., paramN) => { return expression; }
例:
let sum = (x, y) => x + y;
sum(1, 2)
返回值为3
3. 当只有一个参数时,括号可以省略
(param) => { statement }
等价于 param => { statement }
例:
let double = x => x * 2;
double(3)
返回值为6
4. 当没有参数时,需要带上括号
() => { statement }
说明
expression & statement
expression: expression evaluate to a value
statement: statement do something
参考资料
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/
strict mode VS non-strict mode
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- React and React with ES6