Over a million developers have joined DZone.

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
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}