Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Created June 21, 2011 18:06
Show Gist options
  • Save subtleGradient/1038471 to your computer and use it in GitHub Desktop.
Save subtleGradient/1038471 to your computer and use it in GitHub Desktop.
Simple JavaScript Module Pattern
function MyClass(){
if (this instanceof MyClass){
this.init.apply(this, arguments);
} else {
MyClass.from(arguments[0])
}
}
MyClass.from = function(object){
// convert object into a MyClass or something
}
MyClass.prototype = {
constructor: MyClass,
init: function(){
// …
}
}
////////////////////////////////////////////////////////////////////////////////
// Usage
var myMyClass = new MyClass;
var something = { 'random object':true },
somethingAsMyClass = MyClass(something); // same as MyClass.from(something)
function MyClass(){
this.init()
}
MyClass.prototype = {
constructor: MyClass,
init: function(){
// …
}
}
////////////////////////////////////////////////////////////////////////////////
// Usage
var myMyClass = new MyClass;
// BEWARE!
MyClass() // throws 'undefined' is not a function (evaluating 'this.init()')
// That's because without `new`,
// the `this` in the MyClass constructor is the global object (usually window)
// and window.init() probably doesn't do what you expect.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment