Posted By

adrianparr on 04/13/12


Tagged

javascript js method oop function variable property scope self private public Anonymous executing


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

shalomfriss


JS OOP Example using a self-executing anonymous function


 / Published in: ActionScript 3
 

URL: http://www.gotoandlearn.com/play.php?id=159

Watch Lee Brimelow's tutorial on GotoAndLearn to see what this is all about.

  1. <!--
  2. index.html
  3.  
  4. Demo JavaScript file containing a self-executing anonymous function
  5. Taken from a Lee Brimelow tutorial ...
  6. http://www.gotoandlearn.com/play.php?id=159
  7. -->
  8.  
  9. <!DOCTYPE html>
  10. <html lang="en">
  11.  
  12. <head>
  13. <meta charset="utf-8">
  14. <title>OOP JavaScript</title>
  15. <script src="js/Car.js"></script>
  16.  
  17. <script>
  18.  
  19. function init() {
  20. var car = new Car("Audi", "Ranger", "Blue");
  21. car.setMake("Ford");
  22. car.startEngine();
  23. }
  24.  
  25. </script>
  26.  
  27. </head>
  28.  
  29. <body onload="init()">
  30.  
  31. </body>
  32.  
  33. </html>
  34.  
  35.  
  36.  
  37. /////////////////////////////////////////////////////////////////////////
  38. // Car.js
  39. //
  40. // Demo JavaScript file containing a self-executing anonymous function
  41. // Taken from here Lee Brimelow's tutorial ...
  42. // http://www.gotoandlearn.com/play.php?id=159
  43.  
  44. (function(window) {
  45.  
  46. //Public variable/property
  47. Car.prototype.mpg = 30;
  48.  
  49. //Static variable/property
  50. Car.num_of_wheels = 4;
  51.  
  52. //Constructor function/method
  53. function Car($make, $model, $colour) {
  54. //Private variables/properties
  55. var _make = $make;
  56. var _model = $model;
  57. var _colour = $colour;
  58.  
  59. //Public getters
  60. this.getMake = function(){return _make;};
  61. this.getModel = function(){return _model;};
  62. this.getColour = function(){return _colour;};
  63.  
  64. //Public setters
  65. this.setMake = function($make){_make = $make;};
  66. this.setModel = function($model){_model = $model;};
  67. this.setColour = function($colour){_colour = $colour;};
  68. }
  69.  
  70. //Public function/method
  71. Car.prototype.startEngine = function() {
  72. console.log(getDesc(this) + " engine started");
  73. };
  74.  
  75. //Private function/method
  76. function getDesc($context) {
  77. return $context.getMake() + " " + $context.getModel();
  78. }
  79.  
  80. //Make available in the global scope
  81. window.Car = Car;
  82.  
  83. }(window));

Report this snippet  

You need to login to post a comment.