排名前10的ES6特性之箭头函数 【Arrow Functions】
2016-01-05 18:41
537 查看
Ranking(1) 箭头函数 Arrow Functions
【1】 文章的开头先来熟悉几个箭头表示方式。<!-- 表示:单行注释 比如<!-- --> --> 表示:‘趋向于’操作符 while (n --> 0) n趋向0 <= 表示:小于等于 => 这又是什么呢?
【2】Arrow function 语法规则
() => { ... } // no parameter x => { ... } // one parameter (x, y) => { ... } // 多个参数 指定一个函数体 x => { return x * x } // block x => x * x // 等同上一行
【3】 再来看2个例子用以区分传统方法与ES6 。
eg 1:1) 传统方法。
var arr =[1,2,3] var squares = arr.map(function(x){return x*x});
2) arrow functions 应该如何表示呢?
let arr = [1, 2, 3]; let squares = arr.map(x => x * x);
//输出的功能与传统方式一样。
结论一:ES6 的方法比传统的方法的优势之一,减少冗余或是累赘。表述更加清晰。
eg 2:1) 传统方法。
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { // (A) //'use strict'; return arr.map(function (x) { // (B) // Doesn’t work: return this.prefix + x; // (C) }); }; // output :["undefinedJoe", "undefinedAlex"]
//严格模式下,this.prefix 是undefined,
传统方式的解决方案是:
Solution 1: that = this
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { var that = this; // (A) return arr.map(function (x) { return that.prefix + x; }); }; > var pre = new Prefixer('Hi '); > pre.prefixArray(['Joe', 'Alex']); //out put:[ 'Hi Joe', 'Hi Alex' ]
Solution 2: 为this指定值
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + x; }, this); // (A) };
Solution 3: bind(this)
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + x; }.bind(this)); // (A) };
2) arrow functions 有着更加简洁的方式
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map((x) => { return this.prefix + x; }); };
另一种表现形式:
如果采用ES6的构造函数以及利用类的方式,将更加方便简洁
class Prefixer { constructor(prefix) { this.prefix = prefix; } prefixArray(arr) { return arr.map(x => this.prefix + x); // (A) } }
//表现功能与传统方式一样。
在方法和箭头函数之间,我再也不会错写function了,这真是一个绝妙的设计思想!
箭头函数与非箭头函数间还有一个细微的区别,箭头函数不会获取它们自己的arguments对象。
诚然,在ES6中,你可能更多地会使用不定参数和默认参数值这些新特性
除了这样,箭头函数和正常函数之间没有明显的差异。例如,类和实例产生相同的结果:
> typeof (() => {}) 'function' > () => {} instanceof Function true > typeof function () {} 'function' > function () {} instanceof Function true
下一节 讨论 ES6 的 Modules.
相关文章推荐
- java和c++中的DES\3DES\Base64
- activiti查看流程图,有中文乱码
- linux下的C语言基础学习
- iOS图片高斯模糊 毛玻璃效果
- 过去一年 硅谷科技圈发生了这五大变化
- web导出excel文件的几种方法
- CentOS 7.1 NVMe 中断绑定最近的NUMA node
- android解析xml简单分析
- HTML之postion属性
- Asp.Net MVC 使用FileResult导出Excel数据文件
- 初识 Spatial Pyramid Matching
- oracel字符截取substr
- 第3方支付
- Sublime 运行Java
- navicat 链接不上mysql
- Android中捕获TTextView文本中的链接点击事件方法
- lintcode:search a 2d matrix II 搜索二维矩阵II
- 《Spring实战》学习笔记-第一章:Spring之旅
- JNI函数的动态注册
- swustoj---寝室扫地问题509