Javascript local variable declare

2020-02-06 01:29发布

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

8条回答
Rolldiameter
2楼-- · 2020-02-06 02:08

I must be missing something. How is what you want different from just doing:

 var newObject = 'some string';

? (OP has clarified question)

I don't think there is a way to do what you are asking. Use members of a local object, e.g.

function doSomething(name, value)
{
  var X = {};
  X[name] = value;
  if (X.foo == 26)
    alert("you apparently just called doSomething('foo',26)");
}

If you choose a 1-character variable like $ or X, it "costs" you 2 characters (variable name plus a dot), and avoids trying to use eval or doing something weird.

查看更多
Animai°情兽
3楼-- · 2020-02-06 02:13

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;
}
查看更多
登录 后发表回答