Dynamic variable names

R

Russ Chinoy

Hi,

This may be a totally newbie question, but I'm stumped.

If I have a function such as:

function DoSomething(strVarName) {
.....
}

and I call it like so:

DoSomething('myVarName');

Inside the function, how do I assign a value to the variable named myVarName
(i.e. the variable whose name is the value of strVarName)?

Thanks!
Russ
 
M

Mick White

Russ said:
function DoSomething(strVarName) {
....
}

and I call it like so:

DoSomething('myVarName');

Inside the function, how do I assign a value to the variable named myVarName
(i.e. the variable whose name is the value of strVarName)?


window[strVarName]=some value;

Mick
 
L

Lee

Russ Chinoy said:
Hi,

This may be a totally newbie question, but I'm stumped.

If I have a function such as:

function DoSomething(strVarName) {
....
}

and I call it like so:

DoSomething('myVarName');

Inside the function, how do I assign a value to the variable named myVarName
(i.e. the variable whose name is the value of strVarName)?

Wanting to do such a thing seems sort of like a newbie problem.
What are you really trying to do? There must be a better way.
 
T

Thomas 'PointedEars' Lahn

Mick said:
Russ said:
function DoSomething(strVarName) {
....
}

and I call it like so:

DoSomething('myVarName');

Inside the function, how do I assign a value to the variable named
myVarName (i.e. the variable whose name is the value of strVarName)?

window[strVarName]=some value;

No, don't. `window' may be a reference to the Global Object in many
cases, but not in all. Use a reference to the Global Object instead:

var MyVarName = ...;
var _global = this;

function doSomething(strVarName)
{
... _global[strVarName] ...
}

doSomething('myVarName');

If you are concerned that the new global `_global' spoils your global
namespace, you can instead also do

var MyVarName = ...;

function doSomething(strVarName)
{
... doSomething._global[strVarName] ...
}
doSomething._global = this;

doSomething('myVarName');


PointedEars
 
T

Thomas 'PointedEars' Lahn

Mick said:
Russ said:
function DoSomething(strVarName) {
....
}

and I call it like so:

DoSomething('myVarName');

Inside the function, how do I assign a value to the variable named
myVarName (i.e. the variable whose name is the value of strVarName)?

window[strVarName]=some value;

No, don't. `window' may be a reference to the Global Object in many
cases, but not in all. Use a reference to the Global Object instead:

var myVarName = ...;
var _global = this;

function doSomething(strVarName)
{
... _global[strVarName] ...
}

doSomething('myVarName');

If you are concerned that the new global `_global' spoils your global
namespace, you can instead also do

var myVarName = ...;

function doSomething(strVarName)
{
... doSomething._global[strVarName] ...
}
doSomething._global = this;

doSomething('myVarName');


PointedEars
 
R

Richard Cornford

Matt said:
Thomas 'PointedEars' Lahn wrote:
window[strVarName]=some value;
No, don't. `window' may be a reference to the Global Object
in many cases, but not in all.

Out of curiosity, which cases are you referring to?

WSH and (JScript) ASP certainly don't have a global reference to the
global object. This will probably also be true of many embed javascript
engines as the language itself does not make a global reference to the
global object a requirement.

Richard.
 
T

Thomas 'PointedEars' Lahn

Matt said:
Thomas said:
window[strVarName]=some value;
No, don't. `window' may be a reference to the Global Object
in many cases, but not in all.

Out of curiosity, which cases are you referring to?

Out of tiredness, please ask Google (Groups) about this group.
Or maybe Richard or someone else can repeat them to you.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Richard said:
Matt said:
Thomas said:
window[strVarName]=some value;
No, don't. `window' may be a reference to the Global Object
in many cases, but not in all.

Out of curiosity, which cases are you referring to?

WSH and (JScript) ASP certainly don't have a global reference
to the global object.

You got me confused. Does this mean that even

// global context
var _global = this;

does not work there?


PointedEars
 
L

Lasse Reichstein Nielsen

Richard Cornford said:
Matt said:
Thomas 'PointedEars' Lahn wrote:
window[strVarName]=some value;
No, don't. `window' may be a reference to the Global Object
in many cases, but not in all.

Out of curiosity, which cases are you referring to?

.... SVG implementations are another example. I know that the Adobe
SVG plugin has a global window variable referring to an object
separate from the global object.

/L
 
R

Richard Cornford

Thomas said:
You got me confused. Does this mean that even

// global context
var _global = this;

does not work there?

No, that works fine. The - this - keyword refers to the global object
when used in the global execution context and variables declared in the
global execution context are still made into properties of the global
object. It should be possible to create your own global reference to the
global object using that formulation in any ECMA 262 compliant
implementation.

Richard.
 
T

Thomas 'PointedEars' Lahn

Richard said:
Thomas said:
You got me confused. Does this mean that even

// global context
var _global = this;

does not work there?

No, that works fine. [...] It should be possible to create your own
global reference to the global object using that formulation in any
ECMA 262 compliant implementation.

Great, that's what I expected :) Thank you.


\V/ PointedEars
 
V

vallini

Hi Russ, and forgive my english which is not my native language.

I am afraid that somebody here didn't get your point and got lost into
speculation. Pointed ears is one of the biggest pain in the neck ever
seen online period, he answers to nearly everything he sees, he pops up
everywhere, continuously, year after year, on a nearly daily basis, on
nearly 50% of the threads, 99.99% of the times having nothing to say
(the 0.01% is a statistical dispersion), full of formalism, counting in
every single hair he sees on a cheek, and being often full of disdain
(see his answer to Matt), so no wonder he ended up with an entirely new
thread quite unrelated with your question.
Be warned, he has a few friends. They'll show up here promptly.

You're a newbie? If (if) so you want to understand, right?
Your question is:
======
totally newbie question (...)
Inside the function, how do I assign a value to the variable named
myVarName
======
Got it.

Ok, firts it seems to show some confusion that can be quite understood
if as you hint you are a newbie. You are RIGHT, maybe you still do not
know how much, that myVarName is a variable, YET when we define
variables inside the round brackets of a function, we call them
ARGUMENTS, not 'variables', though they ARE such INDEED. Get used to
this.

Ok, why arguments?
To answer this, why functions?

Functions in digital codes derive their name from MATH.
f(x)
in math means that something named 'f' is a FUNCTION of something named
'x': that is, IF x varies, f varies with it (HOW; well, math doesn't
say that with THAT statement, YET codes do: within the CURLY brackets).
It can also be written, in math:
f(x, y)
which now means that the thing called f, whatever it could be, changes
depending on variations no longer only upon something called x,
whatever it could be (try to abstract as much as you can) but also
depending on something ELSE called y.

NOT orthodox at all, but to make you understand:
speed (time, space)
Got it now? :)

If you take notice, that is the same notation used in informatic
functions:

function aname (x, y) {/*here the type of VARIATIONS that shall
occur*/}
or, say
function speed(time, space){return space/time;}

those that are passed in between round brackets are its ARGUMENTS,
namely the parameter(s) upon whose VARIATIONS, the function may return
a VARIED outcome.

It is true that DIGITAL (NOT mathematical) functions can be run also
without arguments. This because, of course, there is a point where
informatic departs from mathematics and takes its own turn and path.
YET, it starts from the same grounds.

So, I want you for a start to understand that a function is called a
function because in its theoretical roots, it should change its OUTCOME
depending on how its ARGUMENTS vary, EXACTLY like a Mathematical
function would: f(x,y).
How these arguments vary? Exactly as you ask, by ASSIGNING to them some
values

Now your question: HOW do you ASSIGN exactly them, namely how do you
INTRODUCE in those SIGNATURES the ACTUAL variations?

When you assign a variable name, for now in a general way later we'll
see within a function, it may be benefical to discriminate about its
components. Let's review, though you may still know.

The variable name: this, as you already know for sure, is written
WITHOUT quotes, and can be whatever name which is not a keyword in the
given language, so say:

foo

now you give to it a value, namely you perform what is called an
ASSIGNMENT:

foo=

what follows is the VALUE. Can be either primitive data type( string,
namely in between quotes, or number, or boolean, or even another
variable previously initialized, or an object or array which latter is
no longer properly 'primitive' to some degree - some may speculate it
is)

foo="hallo";

YET you should prefix in javascript the keyword var

var foo="hallo";

Get this habit.
Note that var defines the scope of a variable. If you use var, the
variable you initialize belongs to the scope where it has been
initialized, namely can be viewed and ACCESSED by all the other code
components that RESIDE WITHIN that SCOPE where it was INITIALIZED.
So,

var foo="hallo"

would be visible to EVERYTHING ELSE in your code, because you
initialized it outside any block of code, in the global scope of your
script that is.

YET if you INSIDE a function do like:

function dunno(){
var foo="hallo"
}

NOW, having used var, foo is visible ONLY within the function named
dunno.

If you would have omitted the prefix var, THEN it would have been
visible as a GLOBAL scope again. It's just a RULE in javascript (for a
newbie it's better to see it like that): if you use var, you define a
scope: WHENEVER you do not use var, the DEFAULT scope is always meant
as the GLOBAL window, NO MATTER where you initialized it.
If you initialize a variable within a function or even a LOOP inside a
function, and you use the keyword var, such variable is VISIBLE and
ACCESSIBLE only and exclusively within the nearest outermost block that
ENCAPSULATES it, got it?
If you do NOT use the keyword var, then whatever variable, NO matter
where it has been initialized, shall belong to the GLOBAL scope.

So, get used to use var to limit the scope of your variable from
tampering with an unnecessarily wide scope, or even dabfgerously
OVERWRITE possible variables with the same name in some outer scope.

More:
A statement like

var foo;

is called a DECLARATION.

a statement like
var foo = "hallo"
namely assigning ALSO the value in the same code line, is called an
INITIALIZATION.

Why all this? Because i want you to UNDERSTAND that those LOGICS FULLY
apply also for variables passed to a function, only the operate a
little bit in "DISGUISE": but if you can see that they are the SAME
thing as above, chances are you understand this once and for all.

Now, to answer your point, when you have arguments in an array
definition like yours

function DoSomething(strVarName) { }

that strVarName is the same as a DECLARATION of a variable.
Please read this line again: that strVarName is the same as a
DECLARATION of a variable.

But it has been added no assignment yet, as you may see yourself.

There are languages, like PHP but NOT Javascriopt, where it would even
be possible to perform INITIALIZATION for ARGUMENTS of a function:

function dunno($foo='hallo'){}

that in PHP means that the argument $dunno has a DEFAULT value which is
'hallo' in CASE the argument is not passed upon INVOKING the function.

This is NOT possible in javascript. In javascript whenever you have a
function and its arguments, the latter can only be DECLARED, never
initialized right ON THE SPOT as for instance PHP could.

So when does this damn assignment of the RELATIVE VALUE occurs?
Upon CALLING the function.

function DoSomething(strVarName) {alert(strVarName);}
//above your function declaration

DoSomething("hallo world"); //assigned!!!!

above, now that you have invoked or called your function DoSomething,
what has happened is the SAME, in the background, than having firstly
DECLARED a variable name whose SCOPE is AUTOMATICALLY within the
FUNCTION scope, and THEN upon CALLING you have performed the
ASSIGNMENT. That is, upon calling
DoSomething("hallo world");
what you have done in the BACKGROUND is like:
var strVarName="hallo world";

Every time you call the function, thus, you can perform a NEW
assignment.

Your sentence, Russ, that goes

========
Inside the function, how do I assign a value to the variable named
myVarName
(i.e. the variable whose name is the value of strVarName)?
========

The way you assign a value to the variable named myVarName (which when
it is a variable inside a function round brackets is called an
ARGUMENT) is the one I just showed to you: by passing the value when
you CALL the function.
This is your answer.

I don't know whether this makes things clearer to you, but it seems at
least a more newbie friendly or oriented explanation, which takes the
time a newbie needs to learn something that RIGHTLY still escapes his
or her grasp. We have all been there so don't worry - well, except of
course Pointed Ears and a couple of others which you will soon meet if
you attend here long enough to be soon disgusted by them.

Good luck Russ, you're doing fine, and asking the right questions.
ciao
Alberto
http://www.unitedscripters.com/
 
M

Matt Kruse

Thomas said:
Matt said:
Thomas said:
window[strVarName]=some value;
No, don't. `window' may be a reference to the Global Object
in many cases, but not in all.
Out of curiosity, which cases are you referring to?
Out of tiredness, please ask Google (Groups) about this group.
Or maybe Richard or someone else can repeat them to you.

Since the assumption in this group is browser scripting in a WWW context (as
is often pointed out) then I assumed you were implying that
window[strVarName] = some value;
would not work correctly in some browsers or contexts.

I see no reason to use

_global = this;

to get a reference to the global object when you are writing for the assumed
browser environment in a WWW context. window[varname] is perfectly fine, and
to discourage its use probably just confuses some people more than helps
them, IMO.
 
V

vallini

Second part: associative arrays.

In Javascript, being "object" oriented, you can access every element
via the dot notation. For instance knowing that a variable is named foo
var foo='hi';
it automatcially belongs to the window object.

Thus, stating:
window.foo
you are doing the same as accessing foo.

Yet, the dot notation is only another way to write what that thing is:
an Object. As such, it is a collection of PROPERTIES.
As everything in OOP which is a collection of properties, it can be
accessed as the KEY of an array (in javascript there is a much closer
relatuons between arrays and objects than in Java!):
window['foo']

Note that I have used quotes (apex). That is if you use the associative
power of the object and you resort to brackets [], the variable name
must be called in as a key, and as such can be either numerical or a
string, If a string, it should gon in between quotes. In fact, for an
object, its keys are all Strings (even NUMBERS are actually liuteral
numbers for a string, namely not say 1 but '1'.
Evidence of this:
var a=[1,2,3];
for(var i in a){alert(typeof i)}

aLl those alerts shall return STRING, because you loop it as an object.
Yet if you'd loop it as an array
for(var i=0; i<a.length;i++){alert((typeof i)+' '+(typeof a))}
that will rerturn NUMBER NUMBER

I don't know of a better evidence that when you deal in an OO language
with a data structure treating it as an OBJECT, then ALL ITS KEYS
belong to the STRING data type.

Now and as a consequence of it, whatever is fit to return a STRING DATA
TYPE, is ALSO fit to be used as the KEY to unlock a property out of an
object. ALSO out of the window object, if a variable belongs to it.

Thus if you say
var foo='foo2';
foo2='hallo world';

if you now say
window[foo]
since foo holds a STRING, it triggers from the window scope the
PROPERTY whose name was the one HELD as a STRING by foo, namely foo2,
so
window[foo]
would return:
"foo2" which, grabbed then as a property of the window scope, would
grab the varbaile NAMED and initialized as foo2 and thus shall
eventually relinquis the VALUE held by the latter: "Hallo world".

In Php you'd have finer ways to do it using the double $$ notation.
Javascript uses other avenues, the one just seen.

Now, as long as you're working with javascript, which is what can be
assumed, you an quite safely refer to the window object.

So the answer object oriented to the question
=====
Inside the function, how do I assign a value to the variable named
myVarName
(i.e. the variable whose name is the value of strVarName)?
=====

is: use the ASSOCIATIVE POWER of an OO language like javascript, and
use square brackets.
If strVarName holds as a STRING the name of another variable, whatever
[strVarName]
notation is then fit to retrieve it as long as you know to which scope
the variable whose name is held as a String by strVarName belongs.
If you know in your application such variable belongs to the window
scope, then use window
window[strVarName]

Exploiting the asscoiative power of objects you can do any sort of
crazy things, which purists would disagree with and that yet you should
know you can do

<script>
function foo(){alert('hi')}

foo['aproperty']='hallo world';

foo();

alert(foo['aproperty'])

</script>

You are the owner of your own application so you should know where in
the Object Oriented hierarchy ladder your variables belong.
In javascript, and given the example you yourself provide, it is quite
normal to assume it fully safely belongs to the window scope - except
in the world of pointed ears of course, where he is busy to imagine all
the possible application environments which are less likely to be
yours, and where he finds plausible to say that the window scope is
unsafe in javascript (gee, LOL), and yet at the same time he presumes
it is exactly in a global scope that your variable resides (which,
actually, you did not specify at all. YOU alone can know your OWN
application!).

ciao and good luck
Alberto
http://www.unitedscripters.com/
 
R

RobG

Second part: associative arrays.

In Javascript, being "object" oriented, you can access every element
via the dot notation. For instance knowing that a variable is named foo
var foo='hi';
it automatcially belongs to the window object.

Any variable that is declared outside the scope of an object becomes a
property of the global object. Variables declared inside functions
that are not prefaced with the 'var' keyword are also added to the
global object.

In the HTML DOM, the window property of the global object is the global
object itself. Borrowing from Thomas' post, try the following in a browser:

var _global = this;
alert( (window === _global) );

It will show 'true' where the host environment has a window object that
is identical to the global object (in every browser I tested I got true).

Not all host environments have a window object, though it's probably
safe to assume that web browsers do.

Thus, stating:
window.foo
you are doing the same as accessing foo.

Yet, the dot notation is only another way to write what that thing is:
an Object. As such, it is a collection of PROPERTIES.
As everything in OOP which is a collection of properties, it can be
accessed as the KEY of an array (in javascript there is a much closer
relatuons between arrays and objects than in Java!):

Arrays *are* objects. They are objects with some special methods
(split, join, concat, etc,) and one special property, length.

Do not think of object properties as 'keys', they are properties. They
do not have any of the special attributes or properties that might be
associated with 'keys' in another language.

If you must, think of them as name/value pairs, where the property is a
name and the value can be anything - a function, object, number, string,
whatever.

window['foo']

The difference between using dot notation and square brackets is that in
dot notation, the value given for the property name is treated
literally, whereas in square bracket notation the value is evaluated to
get the property name.

e.g.

declare some variables in the global scope:

var foo = 'bar';
var bar = 'ooh';


Show the value of the foo property using dot notation:

alert( window.foo ) //--> shows bar


the foo property of the window object has the value 'bar', however:

alert( window[foo] ) //--> shows ooh


because the *value* of foo (that is, bar) is used for the
property name as if we'd written:

alert( window.bar )


We could get the foo property using square brackets using:

alert( window['foo'] ) //--> shows bar


Because we have explicitly used a string.

Note that I have used quotes (apex). That is if you use the associative
power of the object and you resort to brackets [], the variable name
must be called in as a key, and as such can be either numerical or a
string, If a string, it should gon in between quotes. In fact, for an
object, its keys are all Strings (even NUMBERS are actually liuteral
numbers for a string, namely not say 1 but '1'.

So don't think of them as keys, think of them as properties. Array
indexes are strings too.

Evidence of this:
var a=[1,2,3];
for(var i in a){alert(typeof i)}

aLl those alerts shall return STRING, because you loop it as an object.

It *is* an object. Using for..in will get all the properties of the
array, even those that aren't accessible using an index - an array index
is just an array property name that is an integer number within the
range 0 to 2^32 - 2:

var A = [1,2,3]
A.foo = 'bar';

for (x in A) alert(x + ':' + A[x]);

will show: 0:1 1:2 2:3 foo:bar

but:

for (var i=0; i<A.length; ++i) alert(A)

will show 1, 2, 3 because it only accesses the properties with integer
values from 0 to A.length - 1. The special methods of arrays only work
on the properties that are indexes (i.e. numbers), e.g.

alert( A.join() ); // --> shows 1,2,3

the 'foo' property is not a number, so join ignores it.

Yet if you'd loop it as an array
for(var i=0; i<a.length;i++){alert((typeof i)+' '+(typeof a))}
that will rerturn NUMBER NUMBER


That doesn't prove anything, i is declared as a number and nothing is
done to change its type.

I don't know of a better evidence that when you deal in an OO language
with a data structure treating it as an OBJECT, then ALL ITS KEYS
belong to the STRING data type.

The ECMAScript Language Specification states that all object properties
are strings. Experimentation should not required to discover it, though
sometimes doing the exercise produces unexpected results. ;-)


[...]
 
R

Richard Cornford

RobG said:
(e-mail address removed) wrote:
Yet if you'd loop it as an array
for(var i=0; i<a.length;i++){alert((typeof i)+' '+(typeof a))}
that will rerturn NUMBER NUMBER


That doesn't prove anything, i is declared as a number and
nothing is done to change its type.

<snip>

A more meaningful test would be using - for(prop in obj) - at then the
type of the value of prop is not externally defined. If you do:-

var z = [1,2,3,4];
for(var prop in z){
alert((typeof prop));
}

- you get 'string' reported 4 times, which would not be expected to be
the case unless an array's 'array index' property names were strings.

Richard.
 
T

Thomas 'PointedEars' Lahn

Matt said:
Since the assumption in this group is browser scripting in a WWW context
(as is often pointed out) then I assumed you were implying that
window[strVarName] = some value;
would not work correctly in some browsers or contexts.
Probably.

I see no reason to use

_global = this;

to get a reference to the global object when you are writing for the
assumed browser environment in a WWW context.

There is no "assumed browser environment in a WWW context" -- unless one
deliberately wants to exclude visitors not using the "right" user agent.
window[varname] is perfectly fine, and to discourage its use probably just
confuses some people more than helps them, IMO.

No, it does not, it sharpens the sense for the difference between language
and AOM/DOM. `window' is a reference to a non-standard host object of the
AOM and its functionality depends on the host environment. To rely on it
regarding globals is error-prone.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top