• 0

    升級到 Node V4 的7個理由

    jopen 9年前發布 | 13K 次閱讀 Node.js

    前兩天,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 翻譯整理,發布在 Coder資源網,轉載請注明來源。

     本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
     轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
     本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
  • sesese色