node.js 在 nodejs 项目中使用 es6 类的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33063206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
proper way of using es6 classes in a nodejs project
提问by ufk
I'd like to be able to use the cool es6 classes feature of nodejs 4.1.2
我希望能够使用 nodejs 4.1.2 的酷 es6 类功能
I created the following project:
我创建了以下项目:
a.js:
a.js:
class a {
constructor(test) {
a.test=test;
}
}
index.js:
索引.js:
require('./a.js');
var b = new a(5);
as you can see I create a simple class that it's constructor gets a parameter. and in my include i require that class and create a new object based on that class. pretty simple.. but still i'm getting the following error:
如您所见,我创建了一个简单的类,它的构造函数获取一个参数。在我的包含中,我需要该类并基于该类创建一个新对象。很简单..但我仍然收到以下错误:
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/ufk/work-projects/bingo/server/bingo-tiny/index.js:1:63)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
any ideas why ?
任何想法为什么?
回答by smirnov
Or you can run like this:
或者你可以像这样运行:
node --use_strict index.js
node --use_strict index.js
回答by ufk
i'm still confused about why 'use strict' is needed, but this is the code that works:
我仍然对为什么需要“严格使用”感到困惑,但这是有效的代码:
index.js:
索引.js:
"use strict";
var a = require('./a.js');
var b = new a(5);
a.js:
a.js:
"use strict";
class a {
constructor(test) {
a.test=test;
}
}
module.exports=a;

