Last active
August 29, 2015 14:18
-
-
Save zoe-1/d5465682428edc583ccc to your computer and use it in GitHub Desktop.
Modules & Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./lib/index.js | |
// ./test/index.js | |
// Both files above make an object with require module as below. | |
var Version = require('./lib/version'); | |
// Version modified in ./test/index.js | |
Version.register = function (server, options, next) { | |
next('Break plugin'); | |
}; | |
// Changes are seen in Version object of different file ./lib/index.js | |
// How?? | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The singleton nature of node.js required modules is really important to understand.
According to @hueniverse, "required modules are particularly important because they represent a singleton object shared with the entire application". Assignment3 illustrates how required modules in
node.js are important, powerful, and a bit confusing when coming from another object oriented language.
source @hueniverse's Simple node.js code style tips to improve code quality
Assignment3's Use of JS Singleton Design
When completing assignment3 we utilized the singleton nature of node's required modules when running tests. In short, both, ./lib/index.js and ./test/index.js create their own Version objects in separate places. However, they both contain the same value all the time. It is as if their values are synchronized. But, in reality they are just referring to the same object. This illustrates node's require modules singleton design pattern.
Singleton Objects Made Using Required Modules
The above syntax can be used to create objects by requiring modules anywhere in the project.
Because of node's singleton pattern design the objects made from the same module will have the
same value throughout the project. They are singleton objects.
View ./test/index.js
View ./lib/index.js
Notice how ./test/index.js modifies the version object and the results of the modifications are
seen in ./lib/index.js Version object. This is because any object created by node's require('module_file') returns a reference to the same object.
This is the node.js require module singleton design pattern in action.
What is a Singleton Pattern?
source Wikipedie Singleton Pattern
Further Reading
Node.js Singleton Docs