0

我是 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

为什么我得到这个?我只是按照指南。

4

2 回答 2

1

我不确定您遵循的是什么指南,但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();
于 2013-10-21T02:31:04.257 回答
1

首先,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();
于 2013-10-21T02:37:07.860 回答