2

Is there a way in Javascript to retrieve the scope of a function from within that function? This would be the same as the closure a subfunction would get. E.g.

var foo = "exists";

function myFunc(){
 var bar = "also exists";
 console.log(foo);       // "exists"
 console.log(scope.foo); // undefined
 console.log(scope.bar); // "also exists"
}
brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • 1
    Are you talking about `this`? – IsraGab Feb 22 '16 at 19:45
  • In the above code, `this.bar` would be `undefined` rather than `"also exists"`. – brentonstrine Feb 22 '16 at 19:47
  • 2
    No, you cannot get a reference to a scope. They're implicit. – Pointy Feb 22 '16 at 19:48
  • One drastically terrible consequence of the ability to get a reference to a scope and use it like an object reference would be that it'd give you the ability to alias local variables. That would make code optimization vastly more difficult. – Pointy Feb 22 '16 at 19:53
  • to find out what `bar` is from another function you need to `return bar;` from `myFunc()`. Then somewhere else, you can write `var myBar = myFunc(); console.log(myBar); // "also exists"` – colecmc Feb 22 '16 at 20:11
  • @colecmc, I'm not looking to do this from _another_ function, but from within the _same_ function. The reason is that I'm trying to emulate a closure without having to actually define the subfunction in scope. I should probably post another question on that topic, since it seems it's impossible to pass the local scope. – brentonstrine Feb 22 '16 at 20:13
  • I created another question that takes [a higher-level approach to what I was trying to do](http://stackoverflow.com/questions/35563195/is-it-possible-in-javascript-to-create-an-external-closure). – brentonstrine Feb 22 '16 at 20:30
  • Then all you need is 'bar'. Within 'myFunc', it's global. – colecmc Feb 22 '16 at 20:36
  • @colecmc, what I was after was a reference to the scope. The example `scope.bar` was just to clarify what I wanted--the ability to access `bar` through the scope, not `bar` itself. :D – brentonstrine Feb 22 '16 at 20:39

0 Answers0