2013-10-21 7 views
0

나는 Nodejs의 초보자입니다. 지금, 나는 가지고 module.jsNodejs 모듈에 대한 오류

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 

왜 I 나는 가이드를 따라 간다.

답변

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