Created
June 6, 2014 01:51
-
-
Save Williammer/ae3ed07e82b4f0bb41d9 to your computer and use it in GitHub Desktop.
jsPatterns.privateStatic.js
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
// constructor | |
var Gadget = (function () { | |
// static variable/property | |
var counter = 0, | |
NewGadget; | |
// this will become the | |
// new constructor implementation | |
NewGadget = function () { | |
counter += 1; | |
}; | |
// a privileged method | |
NewGadget.prototype.getLastId = function () { | |
return counter; | |
}; | |
// overwrite the constructor | |
return NewGadget; | |
}()); // execute immediately Testing the new implementation: | |
var iphone = new Gadget(); | |
console.log(iphone.getLastId()); // 1 | |
var ipod = new Gadget(); | |
ipod.getLastId(); // 2 | |
var ipad = new Gadget(); | |
ipad.getLastId(); // 3 |
Another combination use of closure and constructor is initiate the constructor inside the closure. And use constructor property to "new" another instance.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More often than not, constructor function define properties rather than variables, so that those properties can be passed to the new instantiated instance.