Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var testFn = function(){
- var arr = [];
- this.addToArray = function(obj){
- arr.push(obj);
- };
- this.triggerArray = function(){
- for(i = 0; i < arr.length; i++){
- arr[i].apply();
- }
- }
- }
- var instance1 = new testFn();
- var instance2 = new testFn();
- instance1.addToArray(function(){console.log("Instance 1 - First Function")});
- instance2.addToArray(function(){console.log("Instance 2 - First Function")});
- instance2.addToArray(function(){console.log("Instance 2 - Second Function")});
- instance2.addToArray(instance1.addToArray.bind(instance1));
- //---------------Test-------------//
- instance2.triggerArray();
- // gets into for loop,
- // instance2.arr has three function objects
- // at i = 0 , executes - Instance 2 - First Function
- // at i = 1 , executes - Instance 2 - Second Function
- // at i = 2 , calls Instance 1 triggerArray()
- // gets into for loop
- // instance1.arr has one function object
- // at i = 0 , executes - Instance 1 - First Function
- // comes out of loop when i = 1 not less then arr.length
- // whats the i value now at instance 2
- // it checks in local scope, closure scope, didn't find it , so checks in global scope
- // at global scope i value will be 1 a
- // at i = 1 , executes - Instance 2 - Second Function
- // at i = 2 , calls Instance 1 triggerArray()
- // goes into infinite loop
- // Thus its important to declare i as var i in for-loop
- // in javascript if var is not declared , it puts in global scope
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement