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:
var property = 'foo';
var value = 'bar';
var obj = {val : window.value};//doesn't work for property id's
var obj[window.property] = obj.val;
alert(obj.foo);//alerts 'bar'
Alternatively, make your constructor accept parameters:
function Foobar(prop,val)
{
this[prop] = val;
}
var obj = new Foobar('foo','bar');
alert(obj.foo);//alerts 'bar'
In my second example, nested objects can use the arguments passed to their 'parent'/containing object like this:
function Foobar(prop,val)
{
Foobar.prop = prop;
Foobar.val = val;
...
this.subObj = {};
this.subObj[Foobar.prop] = Foobar.val;//var prop from scope Foobar, same as window
}
Taking advantage of the fact that variables of functions or objects can be made static, you might even do something like this:
Foobar.prop = (typeof Foobar.prop !== 'undefined' ? Foobar.prop : prop);
//or
Foobar.subObj= {new Foobar};//extending parent object
Foobar.subObj.newProp = 'newVal';