Basically this is a question how to access local scope handler. I trying to achieve something similar for global variable definition like:
window['newObject'] = "some string";
alert(newObject);
but for local scope. Right now only solution I have is using evals:
eval("var newObject='some string'");
But this is really ugly solution... The best one would be like using some reference to local scope like in a window[] solution, but I never heard of any reference to local scope... Any ideas ?
Example goes here:
function x(arg)
{
localScope[arg.name]=arg.value;
alert(sex);
}
x({name:"sex", value:"Male"});
In JavaScript, a variable stores the data value that can be changed later on. Use the reserved keyword var to declare a variable in JavaScript.
A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example: <script>
Local VariableIt can only be used inside the subroutine or code block in which it is declared. The local variable exists until the block of the function is under execution. After that, it will be destroyed automatically.
What you're looking for is called the call object. But according to this, you can't access it directly, so you're out of luck.
Why not create an object in local scope and then use it as a container for any variables you wish to create dynamically?
function x(arg)
{
var localSpace = {};
localSpace[arg.name] = arg.value;
}
Okey I found related question that is talking about what I need...
How can I access local scope dynamically in javascript?
I just remember that in ECMA 262 is only one way to add dynamically local variables to scope using "with" statement (and eval of course), here are solution:
var x=function(obj)
{
with(obj)
{
alert(someObj);
}
}
alert(typeof someObj);
x ( {someObj:"yea"}) ;
alert(typeof someObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With