...

View Full Version : How do I set a variable name from a function parameter



andrew1234
07-19-2009, 11:45 AM
Hi

Is is possible to set a variable name from a function parameter?

Kind of like this but it doesn't work!

Your help is greatly appreciated.

Thanks


function Load(setVar){

setVar="test1";

alert(M);
}

Load(M);

fside
07-19-2009, 03:49 PM
Do you have some more explanation of what it is that you're trying to do? Just in plain English, what are you trying to do?

andrew1234
07-19-2009, 05:10 PM
thanks for the reply

I'm trying to set a variable name through the parameter in the calling function



eg in the script below

1)Load(M) will insert M where setVar is.







Load(M);

function Load(setVar){ //setVar is set to M

setVar="test1"; //setVar becomes M

alert(M);//"test1" alerts
alert(Z);//wont alert because it does not exist
}

venegal
07-19-2009, 05:46 PM
You're talking global variables here, right? They can be accessed through the window object.

Here's your modified code; please mind the last comment:


Load('M');

function Load(setVar){

window[setVar]="test1"; //gobal variable M is set to "test1"

alert(M);//alerts "test1"
alert(Z);//will not only not alert, but throw an exception and halt script execution, since Z is not defined
}

andrew1234
07-19-2009, 06:08 PM
Hi Thanks so much ... thats it


so I see if I replace window to this.

it also works

but does it mean that its only for inside that function --like not using the var?

Thanks so much for the help . I really appreciate it.



Load(M);

function Load(setVar){

this[setVar]="test1";

alert(M);

}

venegal
07-19-2009, 06:15 PM
No, the variable M is not scoped within the function, it's global (if that's what you mean). You can test that by just putting the alert outside of the function.

In fact using "this" instead of "window" here does not make any difference at all, since "this" within a global function refers to the window object.

You have an error in your code though, it has to be Load('M') and not Load(M).

andrew1234
07-19-2009, 06:48 PM
thanks again. you really helped me

fside
07-20-2009, 08:13 PM
thanks again. you really helped me

You're going to think it a dumb question - I realize.

But, uh . . why would you want to do that?

andrew1234
07-23-2009, 05:42 PM
Hi FSIDE sorry for the late reply

To answer you question

Just wanted to know if it could be done and maybe because...


one function gets called twice but each time it must behave at a differently but this function is running twice at the same time.

so I thought that if I choose the Variable names in the peratmter then it would not get confused...

but

I have not learned about making my own objects yet. so I think they might be a better way.

any ideas?

Thanks

Andrew



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum