2013-10-21 71 views
0

我是Nodejs的初學者,我按照指南研究了這個問題。 現在,我有一個module.js關於Nodejs模塊的一個錯誤

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 

爲什麼我知道了嗎?我只是按照指導。

回答

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(); 
+0

對不起,我不小心,謝謝! – HXH

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