tra*_*ega 9 module class node.js
我是一个Nodes.js菜鸟,我正试图让我的头脑围绕模块构造.到目前为止,我有一个模块(testMod.js)定义了这个类构造:
var testModule = {
input : "",
testFunc : function() {
return "You said: " + input;
}
}
exports.test = testModule;
Run Code Online (Sandbox Code Playgroud)
我试图这样调用testFunc()方法:
var test = require("testMod");
test.input = "Hello World";
console.log(test.testFunc);
Run Code Online (Sandbox Code Playgroud)
但我得到一个TypeError:
TypeError: Object #<Object> has no method 'test'
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
Dan*_*del 11
这是一个命名空间问题.马上:
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
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
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... }
Run Code Online (Sandbox Code Playgroud)
或者,而不是exports.test你可以做module.exports = testModule,然后:
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... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4452 次 |
| 最近记录: |