繁体   English   中英

关于Nodejs模块的错误

[英]An Error about Nodejs module

我是Nodejs的初学者,我按照指南研究这个。 现在,我有一个module.js

function Hello()
{
  var name;
  this.setName=function(thyName){
      name=thyName;
  };

  this.sayHello=function()
  {
    console.log("hello,"+name);
  };
};

module.exports=Hello;

getModule.js

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

为什么我这样做?我只是按照指南。

我不确定你关注的是什么指南,但是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();

首先,NodeJS遵循CommonJS规范进行模块实现。 你应该知道它是如何工作的。

其次,如果你想像你编写的那样使用模块,你应该修改你的module.jsgetModule.js如下:

//module.js
module.exports.Hello= Hello;

//getModule.js.js
var Hello = require("./module");
var hello = new Hello();
hello.setName("HXH");
hello.sayHello();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM