JavaScript导出类定义

时间:2016-02-03 19:44:59

标签: javascript class ecmascript-6

我可以在JavaScript中导出类定义吗?例如,

in file" HelloWorld.js":

'use strict';

class HelloWorld {
  constructor(msg = 'Hello World~') {
    this.message = msg;
  }

  sayHi() {
    console.log(this.message);
  }
}

module.exports = HelloWorld;


然后在" index.js"

'use strict';
var HelloWorld = require('HelloWorld');

var myObj = new HelloWorld;
myObj.sayHi();


如果我做"节点index.js",那么我得到以下错误:

  constructor(msg = 'Hello World~') {
                  ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/data/users/soltiho/fbsource/fbcode/video_templates/test_env/index.js:3:18)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

我的节点是v5.5.0

1 个答案:

答案 0 :(得分:0)

Node不支持解构(还),无论如何使用解构都是错误的。导入/导出类没有什么特别之处。像任何其他模块一样导入它:

var myValue = require('myVModule');