ES6-arrows

时间:2022-04-25
本文章向大家介绍ES6-arrows,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

从今天开始记录学习ES6的知识点,这次学习的是新增:Arrow functions

Arrows以=>为简写形式,特点:

  • 语法简洁
  • 文法固定的this对象
  • 总是匿名函数

语法:

() => { ... } // no parameter
x => { ... } // one parameter, an identifier
(x, y) => { ... } // several parameters

例子:

arrows
var odds = evens.map(v => v + 1);
常规函数
var odds = evens.map(function(v){return v + 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)
    });
};

在严格模式下,匿名函数中的this的值为undefined,这也就是为何上面的例子会报错。

解决方法:

常规方法

1.

function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    var that = this; // (A)
    return arr.map(function (x) {
        return that.prefix + x;
    });
};
  1. 利用数组方法最后可以传入参数
function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    return arr.map(function (x) {
        return this.prefix + x;
    }, this); // (A)
};

3.

function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    return arr.map(function (x) {
        return this.prefix + x;
    }.bind(this)); // (A)
};
arrows
function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    return arr.map((x) => {
        return this.prefix + x;
    });
};