Skip to content

Instantly share code, notes, and snippets.

@lizlongnc
Created October 9, 2014 16:24
Show Gist options
  • Select an option

  • Save lizlongnc/e1be4c3dd0ad9803814d to your computer and use it in GitHub Desktop.

Select an option

Save lizlongnc/e1be4c3dd0ad9803814d to your computer and use it in GitHub Desktop.
JS Module and Singleton
JavaScript is a protypal language but has syntax that is more similar to a classical language which can be confusing.
Function as module (using self-executing function ) is a way to do functions better in some instances.
Function as module safeguards against values being exposed b/c it limits scope:
(function () {
var ...
function ...
function ...
}());
This method only allows access to the values it wants you to have access to.
A Module Pattern
var singleton = (function () {
var privateVariable;
function privateFunction(x) {
...privateVariable...
}
return {
firstMethod: function (a, b) {
...privateVariable...
},
secondMethod: function (c) {
...privateFunction() ...
}
};
}());
Recipe: Power Constructors
1. Make an object using any means available:
Object literal
new
Object.create
call another power constructor
2. Define some variables and function
these will become private members of the object that is being constructed
3. Augment the object with privileged methods
a privileged method is a method that is public but closes over the private state
4. Return the object
Step 1 - make an object:
function myPowerConstructor(x) {
var that = otherMaker(x);
}
Step 2 - create secret variables/functions
function myPowerConstructor(x) {
var that = otherMaker(x); // here another constructor(otherMaker()) is being asked to make var that
var secret = f(x);
}
Review: http://javascript.info/tutorial/all-one-constructor-pattern
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment