Frage

Is there a way to reference the next object up the scope chain in Javascript?

So, for example:

var a = 12;
function run() {
  var a = 34;
  alert( a ); //replace "a" with something like "parent.a" so it shows 12 instead of 34
}
run();
War es hilfreich?

Lösung

Nope, there is not. Javascript doesn't expose the scope chain at all really (much to my chagrin; I'd love to be able to write a function that adds variables to the local scope, but alas I can't).

Andere Tipps

The short answer is no. JS have closures that lets you "save" the scope state, but that's not the same. You can read about that here: How do JavaScript closures work?

You could use this trick, assigning the inner a variable as a pseudo static property to the run function:

var a = 12;
function run() {
  run.a = 34; //or arguments.callee.a = 34
  alert( a );
}
run(); //=> 12

If the first a is a global variable in the browser, this is also a possibility:

var a = 12;
function run() {
  var a = 34; //or arguments.callee.a = 34
  alert( window.a ); //global variables are a property of window
}
run(); //=> 12

Other answers are correct, but you should know that ECMA-262 explicitly states that the "scope" object (i.e. lexical environment) can't be referenced or modified directly by script. The only exception is that global variables are made properties of the global (synonymous with window in a browser) object.

Lexical Environments and Environment Record values are purely specification mechanisms and need not correspond to any specific artefact of an ECMAScript implementation. It is impossible for an ECMAScript program to directly access or manipulate such values.

ECMA5 §10.2

Maybe it helps, at least you can insert a backdoor to the inner scope of a context:

function Foo() {
    var a = 123; // much private
    this.b = 456; // much public
    this.eval = function(code) { return eval(code) } // backdoor to inner scope
}
foo = new Foo()
console.log("foo.eval(\"a\": ", foo.eval("a")) // 123
console.log("foo.eval(\"b\": ", foo.eval("b")) // ReferenceError: b is not defined
console.log("foo.eval(\"this.b\": ", foo.eval("this.b")) // 456
console.log("foo.a:", foo.a) // undefined
console.log("foo.b", foo.b) // 456

I think the solution you are looking out for is:

var a = 12;
function run() {

   var a = 34;
   alert(window.a); 

  /*accesses the global window object to which any variable 
      in the global scope gets binded*/
}
run();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top