I'v tried to find the reason of using this line of code
var cc = cc = cc || {};
in Cocos2D JavaScript library for example in this place, but I couldn't find any reasonable reason. Single assignment in terms of settings a default value would be ok but double assignment? Anyone know the reason of that?
This one has been annoying me, so I have has a play and done some tests and here are my findings.
I will show two different pieces of script, that produce two different results, thus explaining why somebody may use one over the other. The reasons for using either however is down to the coder and will be based on the effect they want to happen.
Note, for example purposes I will use actually values rather than empty objects.
Normally, you might expect to see the following example in use:
var cc = cc || 1;
This creates a new variable called cc
and gives either the value of an existing (within the same scope) variable, or a default value of 1
. This method will NOT change the original variable, although in practice it will seemingly have the effect that it has changed as you can not subsequently reference the original due to the fact it has the same name.
This can be tested by using different variable names for example:
var aa;
alert(aa);
var cc = aa || 1;
alert(aa);
alert(cc);
(Example)
Here you can see that aa
never changes.
Next we look at the code in question:
var cc = cc = cc || 1;
This will actually change the original variable AND create a new local one. Again, it is not easy to see the effects while the variables have the same name. However, if we do the same name change as above, we can see the real effect:
var aa;
alert(aa);
var cc = aa = aa || 1;
alert(aa);
alert(cc);
(Example)
This time we can see that aa
does get changed.
In conclusion, you may never actually see any effect from using one over the other (with the same variable names), but I am curious as to what effects would happen if it is possible to reference the original somewhere, prior to assignment, and therefore the choice of which to use would actually have an effect. I will see if I can find something to show this in action.