Created
April 13, 2011 21:12
-
-
Save adamloving/918432 to your computer and use it in GitHub Desktop.
Simulating inheritance with Javascript
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
// I'm not sure which of these is the best, they all have pros and cons. | |
// for more ideas, see http://ejohn.org/blog/simple-javascript-inheritance/ | |
// ----- 1 [using functions as objects with prototypes]----- | |
function MyBaseClass() { }; | |
MyBaseClass.prototype.myMethod = function() { }; | |
function MyClass() { | |
MyBaseClass.call(this); // call base class constructor | |
} | |
// note: prototype is an instance, shared between descendant objects | |
MyClass.prototype = new MyBaseClass(); | |
// ----- 2 [everything's an object instance] ----- | |
var MyBaseClass = { | |
myMethod: function() {} | |
} | |
// everything’s an object... | |
var MyClass = $.extend(MyBaseClass, { | |
myOtherMethod: function() { } | |
}); | |
// ----- 3 [Yahoo API pattern] ----- | |
var MyBaseClass = function() { | |
// do constructor stuff | |
var privateToMyBaseClass = 1; | |
return { | |
someFunction: function() {} | |
} | |
}(); | |
var MyClass = function() { | |
var privateToMyClass = 1; | |
return $.extend(MyBaseClass, { | |
myOtherMethod: function() {} | |
}) | |
}; | |
x = new MyClass(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment