/ Published in: JavaScript
This is a simple example of OOP in Javascript, based off the highly popular Javascript "The Definitive Guide" book by David Flanagan. I will be expanding this example in the future, let me know what you'd like to see. Thanks!
Note: You must have firebug for firefox to see the results of console.log()
Note: You must have firebug for firefox to see the results of console.log()
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Author: Alvin Crespo Topic: OOP in Javascript Reference: Javascript "The Definitive Reference" by David Flanagan NOTES: * Javascript does not support TRUE classes like Java, C++ and C# do. * It is possible to define pseudoclasses in Javascript. A Constructor Method: new Object () Object from Constructors: var array = new Array(12); var today = new Date(); * NEW operator must be followed by the invocation of a function * Function that is designed to be used with the NEW operator is called a constructor * Purpose of the constructor is to initialize a new object */ //Constructor Method //************************************************************************* //Define the constructor function Square(objectW,objectH){ //initializes by using the keyword THIS this.width = objectW; this.height = objectH; //this is how to add a method to a constructor this.area = function(){ console.log("Area as a property/function of Square: " + (this.width * this.height)); } //The above area function works but is not optimal, because each Square will the area as a property //no return statement } //Invoking the constructor to create Square objects //square1 = {width:2, height:4} var square1 = new Square(5,10); //calling a constructors method var sqArea1 = square1.area(); /* About Prototype Object ---------------------------- * Every javascript object includes an internal reference to another object, known as a prototype object */ //creating a prototype Square.prototype.LargerSide = function(){ var result = ''; //inheritance is automatic as part of the process of looking up a property value, thus // width and height can be used if(this.width > this.height){ result = "Width is Larger"; }else if(this.width == this.height){ result = "Width and Height are the same"; }else{ result = "Height is Larger"; } console.log("Area as a prototype/function of Square: " + result); }//end of LargerSide prototype for Square square1.LargerSide(); //*************************************************************************