Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"});
like image 745
Paweł Witkowski Photography Avatar asked Jul 13 '09 13:07

Paweł Witkowski Photography


People also ask

How do I declare a variable in JavaScript?

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.

What is local variable in JavaScript example?

A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example: <script>

Why can't you use a local variable?

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.


3 Answers

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.

like image 174
JW. Avatar answered Oct 23 '22 10:10

JW.


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;
}
like image 38
Sebastian Celis Avatar answered Oct 23 '22 10:10

Sebastian Celis


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);
like image 42
Paweł Witkowski Photography Avatar answered Oct 23 '22 10:10

Paweł Witkowski Photography