排名前10的ES6特性之箭头函数 【Arrow Functions】

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.

原文地址:https://www.cnblogs.com/alplcx/p/5103459.html