Javascript: Simple OOP Inheritance

Simple yet useable javascript oop inheritance.

//Class BASE
!function ($) {
	classBase = function(){}

	$.extend(classBase.prototype, {
		setVar: function(strVar, val){
		   	if ( this[strVar] !== undefined ) {
				this[strVar] = val;
		   	}
		},
		getVar: function(strVar){
		   if ( this[strVar] !== undefined ) {
				return this[strVar];
		   }
		   return null;
		},
	});
}(window.jQuery);

//Your class
!function ($) {
	classServicesProducts = function () {
	    this.init();
	};

	classServicesProducts.prototype = new classBase(); //Important!!!  Extends functionality of classBase to your class

	$.extend(classServicesProducts.prototype, {
			yourFirstName:'',
			yourLastName:'',
			init: function () {
			},
			showMyFullname:function(){
				var _s = this;
				return _s.yourFirstName + '  ' + _s.yourLastName;
			}
	});
}(window.jQuery);

//HOW TO USE
oClass = new classServicesProducts();
oClass.setVar('yourFirstName', 'Juan');
oClass.setVar('yourLastName', 'Dela Cruz');
alert(  oClass.showMyFullname() );

Tags:

Comments are closed.