Archive

Posts Tagged ‘javascript class’

A simple way of creating a javascript class

March 2, 2010 Comments off

Base class Class

js_class.js


/*
* The base class Class
*
* @author:    Costin Trifan
* @date:      02.03.2010
* @license:   MIT License  http://en.wikipedia.org/wiki/MIT_License
* @version:   1.0
*/
var Class = function( parentClass, methods )
{
	/*
	* Check to see if an Object is an Object or an Object Literal
	* @source: http://stackoverflow.com/
	*/
	var isObject = function( _obj )
	{
	  var _test  = _obj;
	  return (  typeof _obj !== 'object' || _obj === null ?
				  false :  
				  (
					(function () {
					  while (!false) {
						if (  Object.getPrototypeOf( _test = Object.getPrototypeOf(_test)  ) === null) {
						  break;
						}      
					  }
					  return Object.getPrototypeOf(_obj) === _test;
					})()
				  )
			  );
	};

	//*[ If no parentClass is provided add methods to the current constructor ]*/
	if ( parentClass == null )
	{
		if ( isObject(methods) ) {
			var _obj = {};
			for (var propName in methods) {
				_obj[propName] = methods[propName];
			}
		}
		return _obj;
	}
	else {
		/*[ If there are methods, add them to the parentClass ]*/
		if (methods != null)
		{
			if ( ! isObject(methods) ) { throw new Error("The methods object should be an instance of an Object or an Object Literal"); }

			for (var propName in methods) {
				parentClass[propName] = methods[propName];
			}

			return parentClass;
		}
		/*[ Else, return an empty object ]*/
		else { return {}; }
	}
};

Example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Creating a Class in JavaScript</title>
</head>
<body>
<script type="text/javascript">
/*
**     EXAMPLES
**************************
*/

/*[ Creating class X ]*/
var X = new Class();

X.m = function() {
	alert('Inside m function');
};

X.m(); // alerts: Inside m function

/*[ Creating class F ]*/
var F = new Class(null, {
	 one : function(){alert('F::one');}
	,two : function(){alert('F::two');}
});

F.one(); // alerts F::one
F.two(); // alerts F::two


/*[ Creating class Z and extending class F ]*/
var Z = new Class(F, {
	 three : function(){alert('F/Z::three');}
	,four : function(){alert('F/Z::four');}
});

F.three(); // == Z.three(); alerts F/Z::three
F.four(); // == Z.four(); alerts F/Z::four

</script>
</body>
</html>
Advertisements
Categories: JavaScript Tags: