I was reading Ben Cherry’s “JavaScript Module Pattern: In-Depth“, and he had some example code that I didn’t quite understand. Under the Cross-File Private State heading, there is some example code that has the following:
var _private = my._private = my._private || {}
This doesn’t seem to be different from writing something like this:
var _private = my._private || {}
What’s happening here and how are these two declarations different?
This line means use
my._privateif it exists, otherwise create a new object and set it tomy._private.More than one assignment expression can be used in a statement. The assignment operator uses (consumes) whatever is to the right of it and produces that value as its output to the left of the variable being assigned. So, in this case, with parentheses for clarity, the above is equivalent to
var _private = (my._private = (my._private || {}))This case is a type of lazy initialization. A less terse version would be:
In this case, it seems that the lazy initialization is more used for anywhere initialization than laziness. In other words, all functions can include this line to safely create or use
my._privatewithout blowing away the existing var.