Angel’s Blog

Someone right now is looking pretty tired, staring at a laptop trying to get inspired…

A little lesson in JS objects


  1. myobject = function(){
  2.     // defining a method_1
  3.     function method_1() {
  4.    
  5.         function sub_method_1() {
  6.             // defining some var (sum_method_1_var) that gonna be used only in the sub_method_1
  7.             var sub_method_1_var = 7;
  8.            
  9.             // accessing the (z) var thats defined in the method_1
  10.             // this is only possible because sub_method_1 is a sub method of method_1, where the z var is defined
  11.             return sub_method_1_var+z;
  12.         }
  13.        
  14.         // defining a var (z) that will be used in method_1 but accessible
  15.         // from each sub method in  method_1
  16.         var z = 1;
  17.        
  18.         // getting the sum of z + sum_method_1_var ( 1+7)
  19.         // output: 8
  20.         var something = sub_method_1();
  21.         return something;
  22.     }
  23.    
  24.     //defing a value with the result from the method_1
  25.     result = method_1();
  26.    
  27.     // all the method defined in return {} will be public and accessible for the "outside world"
  28.     return {
  29.         // defining a public method
  30.         public_method : function() {
  31.             return result;
  32.         }
  33.     };
  34. }
  35. // defining x as myobject
  36. x = new myobject();
  37. // accessing the public_method of myobject (x)
  38. final_result = x.public_method();
  39. // alert the result
  40. alert(final_result);

A very handy tool for testing pieces of JS source is the Execute JS Add-on for Firefox
It’s the fastest and painless way to execute JS and debug if needed :

I hope this example may help someone :)







Sorry, comments are closed.