Saturday, October 15, 2016

JavaScript Object References

Recently people asked me how JavaScript keep references while passing through function parameters including angular promise, underscore and normal JS code. I will provide one example from each section to show how references are passed.

Under Score (Lodash) Example

Some of the Underscore library functions return object reference while other returns new object. e.g. _.find method returns reference of the object that was found. in the following example when we change the value of variable "f.a", it affects "chkUnder" variable. While in case of _.where method, if we change the value of "w.a", it never changes the variable "chkUnder".

var chkUnder = [{ a: 1 }, { a: 2 }, { a: 3 }];
var f = _.find(chkUnder, { a: 2 });
f.a = 22;
var w = _.where(chkUnder, { a: 2 });
w.a = 24;

Method Parameters

In JavaScript, method parameters are passed as,
1- Reference: if parameter is object.
2- Value: if parameter is primitive types.

In the following example there are two global variables, 

  1. globalobject : The object value is changed two times, first time in the beginning of "second" method where the value is changed to "12" and second time in the callback method where the value is changed to "34". Ever time we changed the value of parameter, it changed global object value (even in callback methods). 
  2. globalint: the parameter value is changed in "second" object but it does not effect "globalint" variable because it is passed by value.

Access Parameters on Callback

There are three scenarios when working with promises

Normal Callback

In following example, promised method is called with parameters in "second" method, in call back method, neither local variable nor the parameter of "second" method is accessible.

JavaScript Loop

 In second scenario (as in image below), the promised method is called in the JavaScript for loop, only index is accessible in the callback method. global parameter "param" and local parameter "local" both are not accessible.

Angular and JQuery Each loop

The third scenario is tested with angular and JQuery each loop. This can also be generalized for all the options which calls delegate method like angular or JQuery each loop (function is called as delegate).
In this scenario, all the global or local variables for method "second" are accessible before "$.each" loop.

No comments:

Post a Comment