Node.js の最新版 v5.0.0 で ECMAScript 2015 (ES6) の class を使ってみる。

Node.js の公式ドキュメント ECMAScript 2015 (ES6) | Node.js によると、 class 構文は strict モードでないと使えないとのこと。

また、ES6 モジュール仕様の import export も使ってみたかったけど Node.js ではまだサポートされていなかったので今回はパス (残念)。

サンプルコード

Node.js で動かすための JavaScript コード。

メイン処理 main.js


$ cat main.js

// Node.js は strict モードでないと class が使えない
"use strict";

// Node.js ではまだ import export 構文が使えないので require
var Tomato = require("./tomato");
var Paprika = require("./paprika");

var print = function(v) {
  console.log(v.name + "の税込み価格: " + v.taxInPrice);
  v.discount(); // 値引き処理
  console.log(v.name + "の値引き後の価格: " + v.taxInPrice);
};

// トマト
var t = new Tomato();
t.price = 100;
print(t);

// パプリカ
var p = new Paprika();
p.price = 200;
print(p);

野菜クラス。


$ cat vegetable.js

"use strict";

class Vegetable {

  // コンストラクタ
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }

  // getter ゲッター構文
  get price() {
    return this._price;
  }

  // setter セッター構文
  set price(value) {
    this._price = value;
  }

  // 税込価格を返す
  get taxInPrice() {
    return Math.floor(this._price * 1.08);
  }

  // 値引きする
  discount() {
    // 安心してください。値引きはしません( ̄ー ̄)
  }
}

// クラス名を指定
module.exports = Vegetable;

トマトは、野菜クラスの子クラスとして実装。


$ cat tomato.js

"use strict";

// 親クラスを require
var Vegetable = require("./vegetable");

// 野菜クラスを継承
class Tomato extends Vegetable {

  constructor() {
    // super で親クラスのコンストラクタを呼び出す
    super("トマト");
  }
}

module.exports = Tomato;

パプリカも、野菜クラスの子クラスとして実装。


$ cat paprika.js

"use strict";

// 親クラスを require
var Vegetable = require("./vegetable");

// 野菜クラスを継承
class Paprika extends Vegetable {

  constructor() {
    // super で親クラスのコンストラクタを呼び出す
    super("パプリカ");
  }

  // 親クラスのメソッドをオーバーライド
  discount() {

    // super で親クラスのメソッドを呼び出す
    super.discount();

    // 3割引はあたりまえ!
    this.price = this.price * 0.7;
  }
}

module.exports = Paprika;

サンプルコードを実行した結果


$ node --version
v5.0.0

$ node main.js
トマトの税込み価格: 108
トマトの値引き後の価格: 108
パプリカの税込み価格: 216
パプリカの値引き後の価格: 151

参考資料

tags: node.js javascript

Posted by NI-Lab. (@nilab)