gpt4 book ai didi

javascript - 关于 Nodejs 模块的错误

转载 作者:行者123 更新时间:2023-12-02 18:13:48 25 4
gpt4 key购买 nike

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

关于javascript - 关于 Nodejs 模块的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com