Friday, June 20, 2014

Creating Classes in Javascript

Overview

Javascript is a prototype-based object oriented programming language. Whenever we think of object oriented programming language the first thing that come to our mind is class but prototype-based languages are class-less. Class-based language has classes and instances for the purpose of inheritance where as prototype-based language has objects which directly inherit from other objects.

As Javascript does not contain explicit features to create classes we can gain the advantage of classes using prototype.org library without losing flexibility of prototypes.

Objective


Creating classes in Javascript and executing functions defined in the class dynamically. "Electronics" section has many equipment like "computer", "camera", "television", "music players" etc. Each equipment has its own unique properties and purposes. User may want to know details about particular equipment. Lets take up this example in dynamic virtual world. We have a class electronics which has each equipment as a function. As per customers request we have to present the details of the equipment.

Include prototype.js in your html

<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js" type="text/javascript"></script>

Create a electronics.js file as follows and keep it in scripts folder

var Electronics = Class.create();
Electronics.prototype = {
initialize: function() {
},

computer : function()
{
window.document.write('Inside computer');
},

camera : function()
{
document.write('Inside Camera');
},

television : function()
{
document.write('Inside Television');
},

mobile : function()
{
document.write('Inside mobile');
}
};

To use this file it need to be included in the web page. On the web page where equipment details need to be displayed call below method
<script language="javascript">
var functionName = prompt("Name the equipment from electronic section for details  ?");
var objElectronics = new Electronics();
// The method is executed with below syntax in Javascript
    //objElectronics.mobile();

document.write('Executing function ... ' + functionName + '<br />');

    // print function code on the browser
document.write('Code : - '+ objElectronics[functionName] + '... <br />Function OutPut : ');

    // execute method
objElectronics[functionName ]();
</script>

Output :
Executing function ... mobile
Code : - function () { document.write('Inside mobile'); }...
Function OutPut : Inside mobile

1 comment: