Created
December 21, 2011 20:57
-
-
Save stepheneb/1507667 to your computer and use it in GitHub Desktop.
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
// simple prototypical module | |
(function() { | |
// module namespace and version | |
abc = { version: "0.0.1" }; | |
// abc.q() is the constructor | |
abc.q = function (s){ | |
// the value of s is saved in x which | |
// has a private scope in this closure | |
var x = s | |
// create an empty q object to add | |
// public functions to as properties | |
var q = {}; | |
// public instance functions | |
q.set = function(val) { | |
x = val | |
}; | |
q.get = function(){ | |
return x | |
}; | |
q.d = function(){ | |
return twotimes() | |
}; | |
q.r = function() { | |
q.set(Math.floor(Math.random()*10)); | |
return q.get(); | |
}; | |
// private functions | |
function twotimes(){ | |
return x + x | |
}; | |
// return the q object with the public | |
// functions as properties | |
return q | |
}; | |
})(); | |
// abc.version => '0.0.1' | |
// f = abc.q(4) | |
// g = abc.q(5) | |
// f.get() => 4 | |
// g.get() => 5 | |
// f.d() => 8 | |
// f.set(6) | |
// f.get() => 12 | |
// g.get() => 5 | |
// References: | |
// http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment