2012-01-26 5 views
9

Tôi là Noo.js noob và tôi đang cố gắng tìm hiểu về các cấu trúc mô-đun. Như vậy đến nay tôi có một mô-đun (testMod.js) định nghĩa lớp này xây dựng:Mô-đun xuất khẩu mô-đun lớp Nodes.js

var testModule = { 
    input : "", 
    testFunc : function() { 
     return "You said: " + input; 
    } 
} 

exports.test = testModule; 

tôi cố gắng để gọi testFunc() phương pháp thusly:

var test = require("testMod"); 
test.input = "Hello World"; 
console.log(test.testFunc); 

Nhưng tôi nhận được một Lỗi Loại:

TypeError: Object #<Object> has no method 'test' 

Tôi đang làm gì sai?

Trả lời

11

Đó là vấn đề về không gian tên. Ngay bây giờ:

var test = require("testMod"); // returns module.exports 
test.input = "Hello World"; // sets module.exports.input 
console.log(test.testFunc); // error, there is no module.exports.testFunc 

Bạn có thể làm:

var test = require("testMod"); // returns module.exports 
test.test.input = "Hello World"; // sets module.exports.test.input 
console.log(test.test.testFunc); // returns function(){ return etc... } 

Hoặc, thay vì exports.test bạn có thể làm module.exports = testModule, sau đó:

var test = require("testMod"); // returns module.exports (which is the Object testModule) 
test.input = "Hello World"; // sets module.exports.input 
console.log(test.testFunc); // returns function(){ return etc... } 
+0

tạo ảnh vui nhộn cảm ơn bạn. – travega