WEB资源网

最新鲜的WEB程序员技术文档及相关资源 – Happy Life, Happy Coding!

升级到 Node V4 的7个理由

前两天,Node V4 已经正式发布了。这是它与 io.js 合并后发布的第一个稳定版本,其中有很多新的亮点,添加了ES6。已经有很多关于 ES6 的概述了,我们这篇文章将说明如何使用它们。

1. Template Strings(模版字符串)

如果你曾在 JavaScript 中试图创建一个多行字符串的话,你可能是这么做的:

var message = [
    'The quick brown fox',
    'jumps over',
    'the lazy dog'
].join('\n')

这只适用于少量的文本,当句子比较多的时候就会显得混乱。因此,一个聪明的开发者想出了一个下面这个叫做 multiline 的hack :

var multiline = require('multiline');
var message = multiline(function () {/*
    The quick brown fox
    jumps over
    the lazy dog
*/});

幸运的是,ES6 为我们带来了模版字符串

var message = `
    The quick brown fox
        jumps over
        the lazy dog
`;

此外,它还给我们带来字符串插值:

var name = 'Schroedinger';

// stop doing this ...
var message = 'Hello ' + name + ', how is your cat?';
var message = ['Hello ', name, ', how is your cat?'].join('');
var message = require('util').format('Hello %s, how is your cat?', name);

// and instead do that ...
var message = `Hello ${name}, how is your cat?`;

在 MDN 上查看关于 模版字符串 的细节

2. Classes(类)

ES5 中定义类看起来有些奇怪,并且需要花费一定的时间:

var Pet = function (name) {
    this._name = name;
};

Pet.prototype.sayHello = function () {
    console.log('*scratch*');
};

Object.defineProperty(Pet.prototype, 'name', {
  get: function () {
    return this._name;
  }
});


var Cat = function (name) {
    Pet.call(this, name);
};

require('util').inherits(Cat, Pet);

Cat.prototype.sayHello = function () {
    Pet.prototype.sayHello.call(this);
    console.log('miaaaauw');
};

幸运的是,我们现在可以在 Node 中使用 ES6 语法:

class Pet {
    constructor(name) {
        this._name = name;
    }
    sayHello() {
        console.log('*scratch*');
    }
    get name() {
        return this._name;
    }
}

class Cat extends Pet {
    constructor(name) {
        super(name);
    }
    sayHello() {
        super.sayHello();
        console.log('miaaaauw');
    }
}

扩展关键字,构造函数,调用超级类和属性,是不是非常棒?更多内容,请查看 MDN 综合指南

3. Arrow Functions(箭头函数)

函数中动态绑定的 this 经常会导致一些混乱,人们一般会使用以下方式:

Cat.prototype.notifyListeners = function () {
    var self = this;
    this._listeners.forEach(function (listener) {
        self.notifyListener(listener);
    });
};

// OR

Cat.prototype.notifyListeners = function () {
    this._listeners.forEach(function (listener) {
        this.notifyListener(listener);
    }.bind(this));
};

而现在,你可以直接使用箭头函数:

Cat.prototype.notifyListeners = function () {
    this._listeners.forEach((listener) => {
        this.notifyListener(listener);
    });
};

查看更多有关 箭头函数 的详细信息

4. Object Literals

通过 object literals,你可以使用如下快捷方式:

var age = 10, name = 'Petsy', size = 32;

// instead of this ...
var cat = {
    age: age,
    name: name,
    size: size
};

// ... do this ...
var cat = {
    age,
    name,
    size
};

此外,你还可以自己轻松的为 object literals 添加函数

5. Promises

不再需要依赖第三方的库如 bluebird 或者 Q,你可以使用本地 Promises。有下面这样公开的 API:

var p1 = new Promise(function (resolve, reject) {});
var p2 = Promise.resolve(20);
var p3 = Promise.reject(new Error());
var p4 = Promise.all(p1, p2);
var p5 = Promise.race(p1, p2);

// and obviously
p1.then(() => {}).catch(() => {});

6. String Methods

也有一些新的字符串方法:

// replace `indexOf()` in a number of cases
name.startsWith('a')
name.endsWith('c');
name.includes('b');

// repeat the string three times
name.repeat(3);

去告诉那些使用 Ruby 的孩子!另外,对 Unicode字符串 的处理也更加好了。

7. let and const

猜测下列函数调用的返回值:

var x = 20;
(function () {
    if (x === 20) {
        var x = 30;
    }
    return x;
}()); // -> undefined
Yep, undefined. Replace var with let and you get the expected behaviour:

let x = 20;
(function () {
    if (x === 20) {
        let x = 30;
    }
    return x;
}()); // -> 20

原因:var 是函数作用域,而 let 是块作用域(正如大部分人期待的那样)。因此我们可以说, let 是 var 的变种。你可以在 MDN 获取更多详细信息

彩蛋:Node 现在也支持 const 关键字了,它可以防止你为相同的参考赋予不同的值。

var MY_CONST = 42; // no, no
const MY_CONST = 42; // yes, yes

MY_CONST = 10 // with const, this is no longer possible

总结

Node V4 带来的 ES6 功能远不止这些,但我希望这七个例子已经能够说服你更新并使用新的版本。

还有很多其他的特性(如 maps/sets,、symbols 以及 generators 等)。请确保你已经看过 Node 中关于 ES6 的概述。愉快的升级吧~

via:cli-nerd,本文由 Specs 翻译整理,发布在 WEB资源网,转载请注明来源。

作者
主站点:http://9iphp.com/ 个人简介:http://me.9iphp.com