关于 Nodejs 模块的错误

An Error about Nodejs module

本文关键字:错误 模块 Nodejs 关于      更新时间:2023-09-26

我是 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();