Created
August 25, 2014 12:50
-
-
Save cristobal/98bdc6b432ef751c4835 to your computer and use it in GitHub Desktop.
Subclassing JavaScript
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 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