Created
June 21, 2011 18:06
-
-
Save subtleGradient/1038471 to your computer and use it in GitHub Desktop.
Simple JavaScript Module Pattern
This file contains hidden or 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
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) | |
This file contains hidden or 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
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