Struggling a little to make best use of Node's module/require()/exports set up to do proper OO programming. Is it good practice to create global namespace and not use exports (as in client side js app development)? So, in module (Namespace.Constructor.js):
Namespace = Namespace || {};
Namespace.Constructor = function () {
//initialise
}
Namespace.Constructor.prototype.publicMethod = function () {
// blah blah
}
... and in calling file just use...
requires('Namespace.Constructor');
var object = new Namespace.Constructor();
object.publicMethod();
Thanks
Namespacing is the act of wrapping a set of entities, variables, functions, objects under a single umbrella term. JavaScript has various ways to do that, and seeing the examples will make the concept easier to understand.
Using Namespaces Namespaces are a TypeScript-specific way to organize code. Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .
While namespaces are not deprecated, using namespaces as the code organization mechanism in your code base is not always recommended.
If you're still getting the "Cannot find namespace Context" error, open your package. json file and make sure it contains the following packages in the devDependencies object. Copied! You can try to manually add the lines and re-run npm install .
In node.js, the module location is the namespace, so there's no need to namespace in the code as you've described. I think there are some issues with this, but they are manageable. Node will only expose the code and data that you attach to the module.exports object.
In your example, use the following:
var Constructor = function() {
// initialize
}
Constructor.prototype.publicMethod = function() {}
module.exports = Constructor;
And then, in your calling code:
var Constructor = require('./path/to/constructor.js');
var object = new Constructor();
object.publicMethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With