javascript类声明之间的区别

我试图为node.js创build一个模块,我注意到了一些东西。 例

function Example() { this.property = "something"; } Example.prototype.run = function() { console.log('hello world') } module.exports = Example; 

这个代码说,没有方法运行。 我需要它来声明

 Example.prototype.run = function run() {} 

上class。 为什么会这样呢?

这应该可以正常工作,只要你真的调用构造函数并创build一个对象,就是你如何configuration示例代码:

 var Example = require("./example"); var item = new Example(); item.run(); 

您需要加载模块并实例化类。

Example.js:

 function Example() { this.property = "something"; } Example.prototype.run = function() { console.log('hello world') } module.exports = Example; 

main.js:

 var Example = require("./Example.js"); var example = new Example(); example.run(); 

跑:

 $ node main.js hello world