【问题标题】:node.js class SyntaxError: Unexpected identifiernode.js 类 SyntaxError:意外的标识符
【发布时间】:2017-10-11 17:30:16
【问题描述】:

我在节点上写我的类

class hello {
 function helloworld(){

       console.log('helloworld');


   }



};

但是当我运行我的服务器时,我得到了这个错误

语法错误:意外的标识符

函数 helloworld(id){ ^^^^^^^^^^

语法错误:意外的标识符

【问题讨论】:

  • 去掉;,去掉分号后发生了什么?
  • @C0dekid 还是一样的错误
  • 删除功能词..所有应该都可以工作。

标签: node.js


【解决方案1】:

在 JS 类中定义方法时,不需要使用 function 关键字。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

你可以简单地做。

class hello {
     helloworld () {
        console.log('helloworld');
     }
}

var a = new hello();
a.helloworld();
//to export from file
exports.hello = hello;

然后在其他文件中。

var myClass = require('yourModule');
var a = new myClass.hello();
a.helloworld();

阅读: What is the purpose of Node.js module.exports and how do you use it?

希望这会有所帮助。

【讨论】:

  • 谢谢,但我如何将这些方法导出到其他文件?
猜你喜欢
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2018-03-29
  • 2018-07-19
相关资源
最近更新 更多