最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript local variable declare - Stack Overflow

programmeradmin1浏览0评论

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

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"});
Share Improve this question edited Jul 13, 2009 at 13:14 Paweł Witkowski Photography asked Jul 13, 2009 at 13:06 Paweł Witkowski PhotographyPaweł Witkowski Photography 9581 gold badge14 silver badges25 bronze badges 2
  • I see, you mean is there a Javascript equivalent to php's "variable variable". php.net/manual/en/language.variables.variable.php – Jason S Commented Jul 13, 2009 at 14:42
  • Possible duplicate of JavaScript: Get local variable dynamically by name string – Michał Perłakowski Commented Jan 12, 2016 at 0:39
Add a comment  | 

8 Answers 8

Reset to default 6

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

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.

You could try the named arguments trick
EDIT: This isn't cross browser

function x( {sex:sex, height:height} ) {
    alert( sex );
    alert( height );
}

x( { sex: 'male', height: 'short' } );
x( { height: 'medium', sex: 'female' } );

// male
// short
// female
// medium

Not sure what you need exactly, but here's my 2 cents.

The only way to dynamically create vars in an existing function is the eval method you've already mentioned.

Another option (mentioned by others) is that your function take a context map, and the template access it with dot notation (context.var1)

My final suggestion is the Function constructor. But I have a feeling this may be what you're looking for. (Note that the function constructor suffers from the same problems as an eval call)

var arg1 = "first";
var arg2 = "last";

// This is the body of the function that you want to execute with first
// and last as local variables. It would come from your template
var functionBody = "alert(first + ' ' + last)";

var myCustomFun = new Function(arg1, arg2,  functionBody);

myCustomFun("Mark", "Brown"); // brings up and alert saying "Mark Brown";

Hope it helps

Interesting question, never thought of something like this. But what is the usecase?

The reason you'd want to do something like this, is if you don't know the name of the variable. But then in that case, the only way to access the variable again would be using the same reference object. I.e. you could just use any old object to store data in.

Reading from such a reference object would be interesting for debugging purposes, but I don't see why you'd want to write to it.

Edit:

The example you posted doesn't convince me of the need for access to the local scope, since you still have the name sex hard coded in the alert. This could be implemented as:

function x(arg)
{
  container = {};
  container[arg.name] = arg.value;
  alert(container.sex);
}

Could you elaborate more on the example?

I'm not entirely sure I understand your question. When creating a class x, I generally do this:

function x(args) {
  var _self = this;

  _self.PriviledgedMethod(a) {
      // some code
  }

  function privateMethod(a) {
      // some code
  }
}

var newObject = new x(args);

You can continue to access _self and args since it is closed on by the contained functions.

发布评论

评论列表(0)

  1. 暂无评论