在nodejs项目中使用es6类的正确方法 [英] proper way of using es6 classes in a nodejs project

查看:753
本文介绍了在nodejs项目中使用es6类的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用nodejs的酷ES6类功能4.1.2

I'd like to be able to use the cool es6 classes feature of nodejs 4.1.2

我创建了以下项目:

a.js:

class a {
  constructor(test) {
   a.test=test;
  }
}

index.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)

任何想法为什么? p>

any ideas why ?

推荐答案

我仍然感到困惑,为什么需要使用strict,但这是代码的工作原理:

i'm still confused about why 'use strict' is needed, but this is the code that works:

index.js:

"use strict"; 
var a = require('./a.js');
var b = new a(5);

a.js:

"use strict";
class a {
 constructor(test) {
  a.test=test;
 } 
}
module.exports=a;

这篇关于在nodejs项目中使用es6类的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆