Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created August 25, 2014 12:50
Show Gist options
  • Save cristobal/98bdc6b432ef751c4835 to your computer and use it in GitHub Desktop.
Save cristobal/98bdc6b432ef751c4835 to your computer and use it in GitHub Desktop.
Subclassing JavaScript
function extend(child, parent) {
var F = function () {
this.__construct = function () {
parent.apply(this, arguments);
};
this.constructor = child;
};
F.prototype = parent.prototype;
// append from subclass prototype
var key;
for (key in child.prototype) {
F.prototype[key] = child.prototype[key];
}
// append static props from subclass
for (key in child) {
F[key] = child[key];
}
child.prototype = new F();
child.__super__ = parent.prototype;
}
// Entity class
function Entity(type) {
this.type = type || "entity";
}
Entity.prototype.getType = function () {
return this.type;
};
// Person class
function Person(name) {
this.__construct("person");
this.name = name;
}
Person.prototype.name = function () {
return this.name;
}
extend(Person, Entity); // extend from Entity
// Example
var p = new Person("Guy Person");
p.getType() => "person"
p.getName() => "Guy Person"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment