Javascript 关于Nodejs模块的一个错误
我是Nodejs的初学者,我按照指南学习。 现在,我有了一个Javascript 关于Nodejs模块的一个错误,javascript,node.js,module,Javascript,Node.js,Module,我是Nodejs的初学者,我按照指南学习。 现在,我有了一个module.js function Hello() { var name; this.setName=function(thyName){ name=thyName; }; this.sayHello=function() { console.log("hello,"+name); }; }; module.exports=Hello; var hello = require("./m
module.js
function Hello()
{
var name;
this.setName=function(thyName){
name=thyName;
};
this.sayHello=function()
{
console.log("hello,"+name);
};
};
module.exports=Hello;
var hello = require("./module");
hello.setName("HXH");
hello.sayHello();
和getModule.js
function Hello()
{
var name;
this.setName=function(thyName){
name=thyName;
};
this.sayHello=function()
{
console.log("hello,"+name);
};
};
module.exports=Hello;
var hello = require("./module");
hello.setName("HXH");
hello.sayHello();
但当我跑步时:
d:\nodejs\demo>node getModule.js
我得到了一个错误:
d:\nodejs\demo\getModule.js:2
hello.setName("HXH");
^
TypeError: Object function Hello()
{
var name;
this.setName=function(thyName){
name=thyName;
};
this.sayHello=function()
{
console.log("hello,"+name);
};
} has no method 'setName'
at Object.<anonymous> (d:\nodejs\demo\getModule.js:2:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
d:\nodejs\demo\getModule.js:2
你好,setName(“HXH”);
^
TypeError:对象函数Hello()
{
变量名;
this.setName=函数(thyName){
name=thyName;
};
this.sayHello=function()
{
log(“你好,”+name);
};
}没有方法“setName”
反对。(d:\nodejs\demo\getModule.js:2:7)
在模块处编译(Module.js:456:26)
在Object.Module.\u extensions..js(Module.js:474:10)
在Module.load(Module.js:356:32)
在Function.Module.\u加载(Module.js:312:12)
位于Function.Module.runMain(Module.js:497:10)
启动时(node.js:119:16)
在node.js:901:3
为什么我会得到这个?我只是按照指南来做。我不确定您遵循的是什么指南,但是
module.js
导出了一个类。由于module.js
导出一个类,当您执行require('./module')
时,您将得到一个类。但是,您使用的是您得到的类,就好像它是该类的实例一样。如果您想要一个实例,您需要像这样使用new
:
var Hello = require('./module'); // Hello is the class
var hello = new Hello(); // hello is an instance of the class Hello
hello.setName("HXH");
hello.sayHello();
首先,NodeJ遵循模块实现规范。你应该知道它是怎么工作的
其次,如果您想像您编写的那样使用模块,您应该修改module.js
和getModule.js
,如下所示:
//module.js
module.exports.Hello= Hello;
//getModule.js.js
var Hello = require("./module");
var hello = new Hello();
hello.setName("HXH");
hello.sayHello();