Search code examples
javascriptvariablesdefinitionlocal

Javascript local variable declare


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"});

Solution

  • 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);