Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 6, 2014 01:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williammer/ae3ed07e82b4f0bb41d9 to your computer and use it in GitHub Desktop.
Save Williammer/ae3ed07e82b4f0bb41d9 to your computer and use it in GitHub Desktop.
jsPatterns.privateStatic.js
// 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
@Williammer
Copy link
Author

  1. constructor function cannot be closure also, the nearest way to do is to turn it into immediate call function and define a new constructor function inside. This way enable both prototype and closure power.
    More often than not, constructor function define properties rather than variables, so that those properties can be passed to the new instantiated instance.

@Williammer
Copy link
Author

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