8

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"});
  • I see, you mean is there a Javascript equivalent to php's "variable variable". http://www.php.net/manual/en/language.variables.variable.php – Jason S Jul 13 '09 at 14:42
  • Possible duplicate of [JavaScript: Get local variable dynamically by name string](http://stackoverflow.com/questions/1920867/javascript-get-local-variable-dynamically-by-name-string) – Michał Perłakowski Jan 12 '16 at 00:39

8 Answers8

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.

JW.
  • 50,691
  • 36
  • 115
  • 143
  • I've never heard the term _call object_ before, but the link you provided was useful. It looks like a JavaScript implementation detail for describing the local scope of a function (that can escape "local" scope by being captured in a closure). However, I don't think this has very much to do with the original question. – Tom Lokhorst Jul 13 '09 at 15:35
  • On second thought, if you _could_ directly access that implementation detail, it would be relevant to the question, so you're right in that respect. – Tom Lokhorst Jul 13 '09 at 15:37
  • Right; if you could, you could do what he's asking: "localScope[name]=value;" – JW. Jul 13 '09 at 17:00
1

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.

Jason S
  • 184,598
  • 164
  • 608
  • 970
1

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;
}
Sebastian Celis
  • 12,185
  • 6
  • 36
  • 44
  • But I need to be able to refer to element as a name only, not with localSpace[name] before every variable... – Paweł Witkowski Photography Jul 13 '09 at 13:34
  • because third parties would like to refer in templates to their own values from local scope... well explaining this is really complicated, but I can sure you that there is no other way of doing this only by having local scope extended (or global but with longer access to variables). – Paweł Witkowski Photography Jul 13 '09 at 22:57
1

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);
Community
  • 1
  • 1
  • 1
    The only thing this `with` block gives you, is that you don't have to write `alert(obj.someObj)`. At the expense of adding three extra lines of code. – Tom Lokhorst Jul 13 '09 at 13:36
  • 1
    "with" is a bad thing to use. See http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/ and https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Object_Manipulation_Statements – Jason S Jul 13 '09 at 14:38
  • Yes - both of those problems : readability and little slower local scope access is affordable with templatings system that I need to create. – Paweł Witkowski Photography Jul 13 '09 at 16:29
  • 1
    Wait: where does the "alert(someObj)" code come from? Are you writing it yourself or is this automatically generated code? Why can't you use alert(obj.someObj) ? – Jason S Jul 13 '09 at 17:55
  • @Jason S: Exactly my point, it seems the OP either can't generate this, or finds it "too much code" to type. I'd say added the extra "`obj.`"-prefix is clearer, since the actual arguments to the function aren't in scope either: `alert(fakeScope.myVar);` – Tom Lokhorst Jul 13 '09 at 18:44
  • content of alert would be outside of a function, and would refeer to something from local scope that should be passed to function... Its really complicated to tell you why is that :)) really :) – Paweł Witkowski Photography Jul 13 '09 at 22:59
  • `with` doesn't inject variables into the local scope; it creates a new scope and pushes it onto the stack. Only `var` and `let` insert variables into the current scope. – Hello71 Feb 25 '11 at 01:14
1

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
meouw
  • 41,754
  • 10
  • 52
  • 69
  • intriguing... is this ECMAscript, or just a particular dialect? (e.g. Spidermonkey since it seems to work with Spidermonkey 1.7) – Jason S Jul 13 '09 at 14:41
  • Interesting one.. I adding +1 :) – Paweł Witkowski Photography Jul 13 '09 at 16:27
  • This is part of JS1.7 and is called destructuring assignment. You can simplify this function declaration to: function x({sex, height}) { ... } – Prestaul Jul 13 '09 at 18:53
  • Doc on destructuring assignment is at [destructuring assignment](https://developer.mozilla.org/en/new_in_javascript_1.7#Destructuring_assignment_%28Merge_into_own_page.2fsection%29). Unfortunately its not part of ECMA 5, but it's in the [harmony proposals](http://www.2ality.com/2011/04/ecmascriptnext-features-are-taking.html) so it might show up in the future. – studgeek May 14 '11 at 14:55
  • This is not solving the OP's question, since they could as well do `function x(sex, height)` and call it appropriately... – xixixao Jan 09 '13 at 03:43
1

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

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

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?

Tom Lokhorst
  • 13,658
  • 5
  • 55
  • 71
-1

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.

Jacob Lauzier
  • 865
  • 6
  • 3