Thursday, February 2, 2012

Javascript Object and Variable Scope

We've been trying to come up with a template for building Javascript objects successfully as we transition from using .NET WebControls to a UI entirely written in Javascript.  We came across the following interesting example of how Javascript variable scope can sometimes be frustrating and confusing.

Consider the following Javascript object definition:



myObjCreator keeps a single variable in scope, and then provides a single selector and mutator for accessing that variable.  It also exposes the variable directly, and this is where the fun begins.

If you believe that variables get passed by reference when assigned to Javascript objects, you would expect to see the following output:
  1
  1
  2
  2
  3
  3

However, if you click the handy dandy "Result" button above, you'll see the output is instead:
  1
  1
  2
  1
  2
  3

What's going on, here?!?

This appears to be proof that assignment to a Javascript object is done by value, not by reference.  Meaning that myObjCreator's internal variable x and the variable o.x are not references to the same internal memory location.  They are different variables.

Here's another example that proves this beyond a doubt:





After assigning x to ret, we modify x to 5.  Yet, when we look at ret.x, it still has the value 1.  So when we did the assignment of x to ret, what was stored was a copy of the value of x, not a reference to the variable x.

Our solution to this problem is to structure our objects to address internal and external references to public variables the same way.  To correct our example, we would write:




Now we get the output we originally expected.

And there was much rejoicing.