Not sure what to search for here, so apologies if I'm repeating another question.
I'm wondering if there are any issues that I'm not aware of with using the following syntax in JavaScript:
var a = {};
var b = a.niceCoat = {};
开发者_C百科
Seems handy, but I just want to make sure...
That is perfectly fine, because a
was declared previously. The expressions will be evaluated as
var a = {};
var b = (a.niceCoat = {});
I.e. it first assigns a new empty object to a.niceCoat
and the result (the result of an assignment is the assigned value) to b
.
But be aware of something like
var a = b = 'c';
which, again, is evaluated as
var a = (b = 'c');
Only a
will be in local scope, b
would be global. If you want b
to be local too, you have to declare it beforehand: var b;
. Something like var a = var b = ....
does not work (not valid syntax).
Slightly off topic:
This method is indeed handy. Imaging you have an object of objects, something like:
var map = {
foo: {},
bar: {}
};
and you want to get the object for a certain key or create a new one if the key does not exists. Normally one would probably do:
var obj = map[key];
if(!obj) { // works because if the key is set, it is an object
obj = {}; // which evals to true
map[key] = obj;
}
// now work with obj
With the above method, this can be shortened to
var obj = map[key];
if(!obj) {
map[key] = obj = {};
}
And we can make it even shorter with the logical OR operator (||
):
var obj = map[key] || (map[key] = {});
(though it might be less readable).
You can do that. a.niceCoat = {}
will be evaluated first, which assigns the object to the property and also has the object as result, which you then can assign to the variable.
You should however be aware that b
and a.niceCoat
are now referencing the same object, so if you put anything in the object it will show up for both the variable and the property:
var a = {};
var b = a.niceCoat = {};
b.x = 42;
alert(a.niceCoat.x); // shows 42
There no issue with that. It's the same as:
var b = (a.niceCoat = {});
Which is the same as:
a.niceCoat = {};
var b = a.niceCoat; // Now b and a.niceCoat are the same object
Just be careful with declaring entirely new variables with it like:
var i = j = 0;
Which is the same as:
j = 0;
var i = j;
Notice how j is not declared with the var
keyword.
this is how you create an empty object in javascript. nothing wrong with it.
Yep, absolutely valid.
E.g.
var a = {};
var b = a.niceCoat = {};
a.foo = function() { alert('foo!'); };
a.foo(); // shows the alert
精彩评论