Skip to content

Instantly share code, notes, and snippets.

@adamloving
Created April 13, 2011 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamloving/918432 to your computer and use it in GitHub Desktop.
Save adamloving/918432 to your computer and use it in GitHub Desktop.
Simulating inheritance with Javascript
// 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