var glb = new Object();
function newVariable(name, val){
glb.name = val;
}
Won't work as expected, you'll need to use glb[name] = val; And as toicontien pointed out, you can extend that to window[name] = val, but I wouldn't recommend either using that many global variables that you need a function to define them, or using a function to define them unless you've a very good reason.
Last edited by Declan1991; 10-09-2011 at 12:31 PM.
Reason: Better phrasing
Great wit and madness are near allied, and fine a line their bounds divide.
glb[name] should be used if "glb" has to be used as an array.
Here my intention is to use glb as an object and thereafter use it's custom "attributes" of glb object as variables.
I didn't understand as to how this can give some unexpected result. Can you give an example so that I can understand this better?
Can you give an example so that I can understand this better?
Example 1
Code:
function newVariable(name, val){
glb.name = val;
}
newVariable('FirstName','Joe')
Will set to the object a property called name, with the value Joe
While in Example 2
Code:
function newVariable(name, val){
glb[name] = val;
}
newVariable('FirstName','Joe');
Will set a property called FirstName, with the value Joe
In the first example, in newVariable(name) it is an argument passed to a function, while in glb.name it is something different: a new property of the object. No relationship between the those two name there
Originally Posted by krismvk1998
glb[name] should be used if "glb" has to be used as an array.
Kor has a great explanation there, but just to add a little to it: using the following syntax,
window["document"]["getElementById"](id)
has nothing to do with arrays, although it looks similar. Arrays are 0-index and the keys must be numeric. In that sense, there is no such thing as an associative array in JavaScript, merely numeric arrays and objects with properties.
Great wit and madness are near allied, and fine a line their bounds divide.
Bookmarks