Advertisement
sanjay1909

var usage Javascript

Jan 13th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var testFn = function(){
  2.     var arr = [];
  3.     this.addToArray = function(obj){
  4.         arr.push(obj);
  5.     };
  6.     this.triggerArray = function(){
  7.         for(i = 0; i < arr.length; i++){
  8.             arr[i].apply();
  9.         }
  10.     }
  11. }
  12.  
  13. var instance1 = new testFn();
  14. var instance2 = new testFn();
  15. instance1.addToArray(function(){console.log("Instance 1 - First Function")});
  16. instance2.addToArray(function(){console.log("Instance 2 - First Function")});
  17. instance2.addToArray(function(){console.log("Instance 2 - Second Function")});
  18. instance2.addToArray(instance1.addToArray.bind(instance1));
  19.  
  20. //---------------Test-------------//
  21. instance2.triggerArray();
  22. // gets into for loop,
  23. // instance2.arr has three function objects
  24. // at i = 0 , executes - Instance 2 - First Function
  25. // at i = 1 , executes - Instance 2 - Second Function
  26. // at i = 2 , calls Instance 1 triggerArray()
  27.     // gets into for loop
  28.     // instance1.arr has one function object
  29.     // at i = 0 , executes - Instance 1 - First Function
  30.     // comes out of loop when i = 1 not less then arr.length
  31. // whats the i value now at instance 2
  32. // it checks in local scope, closure scope, didn't find it , so checks in global scope
  33. // at global scope i value will be 1 a
  34. // at i = 1 , executes - Instance 2 - Second Function
  35. // at i = 2 , calls Instance 1 triggerArray()
  36.     // goes into infinite loop
  37.  
  38. // Thus its important to declare i as var i in for-loop
  39. // in javascript if var is not declared , it puts in global scope
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement