Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript类声明之间的差异_Javascript_Node.js - Fatal编程技术网

javascript类声明之间的差异

javascript类声明之间的差异,javascript,node.js,Javascript,Node.js,我试图为node.js创建一个模块,我注意到了一些东西。范例 function Example() { this.property = "something"; } Example.prototype.run = function() { console.log('hello world') } module.exports = Example; 这段代码说明没有方法运行。我需要它来申报 Example.prototype.run = function run() {

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

function Example() {
     this.property = "something";

}

Example.prototype.run = function() {
     console.log('hello world')
}

module.exports = Example;
这段代码说明没有方法运行。我需要它来申报

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

工作。为什么会发生这种情况?

只要您实际调用构造函数并创建一个对象(这就是您配置示例代码的方式),这应该可以正常工作:

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();
运行:


你打算怎么办?它工作得非常好:
var-Example=require('./Example.js');新示例().run()
$ node main.js
hello world