在 NodeJS 應用程式上使用 JS es6

JS es6(也稱為 es2015)是 JS 語言的一組新功能,旨在使其在使用 OOP 或面對現代開發任務時更加直觀。

先決條件:

  1. 檢視 http://es6-features.org 上的新 es6 功能 - 如果你真的打算在下一個 NodeJS 應用程式中使用它,它可能會向你說明

  2. http://node.green 上檢查節點版本的相容級別

  3. 如果一切正常 - 讓我們的程式碼開啟!

這是一個使用 JS es6 的簡單 hello world 應用程式的非常簡短的示例

'use strict'

class Program
{
    constructor()
    {
        this.message = 'hello es6 :)';
    }

    print()
    {
        setTimeout(() =>
        {
            console.log(this.message);
            
            this.print();

        }, Math.random() * 1000);
    }
}

new Program().print();

你可以執行此程式並觀察它如何反覆列印相同的訊息。

現在..讓我們逐行分解:

'use strict'

如果你打算使用 js es6,則實際需要此行。故意,strict 模式與普通程式碼有不同的語義(請在 MDN 上閱讀更多相關資訊 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)

class Program

難以置信 - 一個 class 關鍵字! 只是為了快速參考 - 在 es6 之前,在 js 中定義類的唯一方法是使用… function 關鍵字!

function MyClass() // class definition
{

}

var myClassObject = new MyClass(); // generating a new object with a type of MyClass

使用 OOP 時,類是一種非常基本的能力,可以幫助開發人員代表系統的特定部分(當程式碼變大時,分解程式碼至關重要……例如:編寫伺服器端程式碼時)

constructor()
{
    this.message = 'hello es6 :)';
}

你必須承認 - 這非常直觀! 這是我類的成員 - 每次從這個特定的類建立一個物件時,這個獨特的函式就會出現(在我們的程式中 - 只有一次)

print()
{
    setTimeout(() => // this is an 'arrow' function
    {
        console.log(this.message);
        
        this.print(); // here we call the 'print' method from the class template itself (a recursion in this particular case)

    }, Math.random() * 1000);
}

因為 print 是在類範圍中定義的 - 它實際上是一個方法 - 可以從類的物件或類本身中呼叫它!

所以……直到現在我們定義了我們的類…時間使用它:

new Program().print();

這真的等於:

var prog = new Program(); // define a new object of type 'Program'

prog.print(); // use the program to print itself

總結: JS es6 可以簡化你的程式碼 - 讓它更直觀,更容易理解(與之前的 JS 版本相比)..你可能會嘗試重寫你現有的程式碼,看看你自己的差異

請享用 :)