Skip to content

Instantly share code, notes, and snippets.

@alcuadrado
Created August 12, 2010 08:06
Show Gist options
  • Save alcuadrado/520547 to your computer and use it in GitHub Desktop.
Save alcuadrado/520547 to your computer and use it in GitHub Desktop.
Prototypal inheritance with automatic initialization in JavaScript
"use strict"; //Remove if using non-strict compatible libraries.
(function (undefined) {
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var createMethod = function () {
var obj = Object.create(this);
obj.initialize.apply(obj, arguments);
return obj;
};
function createBasePrototype(prototype) {
if (prototype.initialize === undefined) {
prototype.initialize = function () {};
}
prototype.create = createMethod;
return prototype;
}
function createDerivedPrototype(parent, atributes) {
var prototype = Object.create(parent);
for (var propertyName in atributes) {
prototype[propertyName] = atributes[propertyName];
}
if (! prototype.hasOwnProperty('initialize')) {
prototype.create = createMethod;
} else {
prototype.create = function () {
var obj = Object.create(this),
args = Array.prototype.slice.call(arguments);
args = [parent].concat(args);
obj.initialize.apply(obj, args);
return obj;
};
}
return prototype;
}
Object.extend = function () {
if (arguments[1] === undefined) {
return createBasePrototype(arguments[0]);
} else {
return createDerivedPrototype(arguments[0], arguments[1]);
}
};
})();
var Person = Object.extend({
initialize: function (name) {
this.name = name;
},
name: "no-name"
});
var Superhero = Object.extend(Person, {
initialize: function (parent, name, realName) {
parent.initialize.call(this, name);
this.realName = realName;
},
realName: "no-real-name"
});
var john = Person.create("John Doe"),
superMan = Superhero.create("Superman", "Clark Kent");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment