Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  86] [ 7]  / answers: 1 / hits: 78374  / 12 Years ago, tue, september 18, 2012, 12:00:00

Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in the same directory. Can I simply export this object with the module.exports object and require() it in the other .js file? If this is possible can you give me an example?



If it helps I'm developing with node.


More From » oop

 Answers
15

This is the way I create modules:



myModule.js



var MyObject = function() {

// This is private because it is not being return
var _privateFunction = function(param1, param2) {
...
return;
}

var function1 = function(param1, callback) {
...
callback(err, results);
}

var function2 = function(param1, param2, callback) {
...
callback(err, results);
}

return {
function1: function1
,function2: function2
}
}();

module.exports = MyObject;


And to use this module in another JS file, you can simply use require and use your object as normal:



someFile.js



var myObject = require('myModule');

myObject.function1(param1, function(err, result) {
...
});

[#83040] Sunday, September 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;