DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Javascript Inheritance
Basic sample of hacking inheritance into Javascript as well as demonstrating the usage of getters and setters
Function.prototype.inherits = function(fnParent) {
this.prototype.super = fnParent;
for (var s in fnParent.prototype) {
this.prototype[s] = fnParent.prototype[s];
}
return this;
}
parentClass = function (args) {
this._name = '';
this.__defineGetter__("name", function(){
return this._name;
});
this.__defineSetter__("name", function(val){
this._name = val.replace('t','p');
return;
});
}
childClass = function (args) {
this.super(args); //constructor for super
}.inherits( parentClass );
var test = new childClass( );
test.name = 'test';
alert( test.name ); //returns pest





