I want to define the following object in javascript:
var property = 'foo';
var value = 'bar';
var obj = {
property: value;
};
This will result the following:
obj.property <-> 'bar';
obj.foo <-> undefined
This is normal, but how to define the object to get:
obj.foo = 'bar';
Possible solution is:
var obj = {};
obj[property] = value;
or
var obj = new Object();
obj[property] = value;
But this is not convient when have to define objects like:
var obj = {
o1: {
oo1: {
property: value;
}
}
};
Again, what I want is:
var property = 'foo';
var value = 'bar';
var obj = {
property: value;
};
alert(obj.foo); // I want this to alert: 'bar'
How you handle similar situations?
Thanks!
If I understand correctly, you want to use variables from the global scope in your object’s constructor several levels deep. Apart from that being, well, risky to put it politely, since there it isn’t really possible to be sure about the value of these variables, you could specify the scope like so:
Alternatively, make your constructor accept parameters:
In my second example, nested objects can use the arguments passed to their ‘parent’/containing object like this:
Taking advantage of the fact that variables of functions or objects can be made static, you might even do something like this: