Javascript OOP Example (Constructor Version)


/ Published in: JavaScript
Save to your folder(s)

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()


Copy this code and paste it in your HTML
  1. /*
  2. Author: Alvin Crespo
  3. Topic: OOP in Javascript
  4. Reference: Javascript "The Definitive Reference" by David Flanagan
  5.  
  6. NOTES:
  7. * Javascript does not support TRUE classes like Java, C++ and C# do.
  8. * It is possible to define pseudoclasses in Javascript.
  9.  
  10. A Constructor Method:
  11. new Object ()
  12.  
  13. Object from Constructors:
  14. var array = new Array(12);
  15. var today = new Date();
  16.  
  17. * NEW operator must be followed by the invocation of a function
  18. * Function that is designed to be used with the NEW operator is called a constructor
  19. * Purpose of the constructor is to initialize a new object
  20. */
  21.  
  22. //Constructor Method
  23. //*************************************************************************
  24. //Define the constructor
  25. function Square(objectW,objectH){
  26.  
  27. //initializes by using the keyword THIS
  28. this.width = objectW;
  29. this.height = objectH;
  30.  
  31. //this is how to add a method to a constructor
  32. this.area = function(){ console.log("Area as a property/function of Square: " + (this.width * this.height)); }
  33. //The above area function works but is not optimal, because each Square will the area as a property
  34.  
  35. //no return statement
  36. }
  37.  
  38. //Invoking the constructor to create Square objects
  39. //square1 = {width:2, height:4}
  40. var square1 = new Square(5,10);
  41. //calling a constructors method
  42. var sqArea1 = square1.area();
  43.  
  44. /*
  45. About Prototype Object
  46. ----------------------------
  47.  
  48. * Every javascript object includes an internal reference to
  49. another object, known as a prototype object
  50. */
  51.  
  52. //creating a prototype
  53. Square.prototype.LargerSide = function(){
  54. var result = '';
  55. //inheritance is automatic as part of the process of looking up a property value, thus
  56. // width and height can be used
  57. if(this.width > this.height){
  58. result = "Width is Larger";
  59. }else if(this.width == this.height){
  60. result = "Width and Height are the same";
  61. }else{
  62. result = "Height is Larger";
  63. }
  64.  
  65. console.log("Area as a prototype/function of Square: " + result);
  66. }//end of LargerSide prototype for Square
  67.  
  68. square1.LargerSide();
  69. //*************************************************************************

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.