Building Classes in JavaScript


Building Classes is quite fun,you can create a simple library,that you will reuse,besides as a developer,repeating the same code is a no-no.DRY(Don’t Repeat Yourself).so as you know JavaScript unlike Java,PHP is a Prototype Programming Language, which according to Wikipedia
“Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming.”

So in short words we will create a class to emulator the Vector Class in Java
//lets create a sample class called Vector
function Vector() //You Create Class in JavaScript with the Keyword function
{[]; //this refers to the Class Vector,and it assigns Vector the variable data which we now declares as an Array “[]”
Vector.prototype.size=function() //The Protoype keywords binds a method or variable to a Class either New or Existing
//This declares size a function
return; //This will return the length of the Array

Vector.prototype.elementAt=function(i) //This creates a function with an argument
var[i]; //assigns the array using the argument as an index
return (data === undefined | null)? “Array Out of Bound Occurred”[i];

Vector.prototype.clear=function() //this clears the Array
Vector.prototype.addElement=function(i) //Creates a function that inserts elements to the Array
{; //Pushes the Element to the Array
var Vector=new Vector(); //Initializes the Class
Vector.addElement(1); //Adds 1 to the Element
Vector.addElement(“String”); //Adds String to the Element
Vector.addElement(2); //Adds 2 to the Element
console.log(Vector.size()); //Returns 3
console.log(Vector.elementAt(3)); //Prints Array out of bound

With this skills,you can create Web Applications as Objects,that makes Web Applications easy to manage,as altering the Base will affect all Objects inheriting from it.Next time will be on Inheritance and Faking Private variables.


Nice post.


Very cool . . . a Javascript and PHP master who knows Java also . . . mehn, you good.