0

Example:

let boo = {
    'foo' : function() {
        let bar = 94;
    }
} 

I want to access bar variable outside function scope. Can anyone help me please?

srinivas
  • 155
  • 1
  • 2
  • 10
  • Declare `bar` in the scope that it will be required – Phil Nov 28 '17 at 04:36
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Phil Nov 28 '17 at 04:37
  • Get your `boo` then call `foo` and find out where the `bar` is located. First you must set `bar` with `this.bar` – Jay Harris Nov 28 '17 at 04:37
  • 1
    `this.bar = 94;` `(new boo.foo()).bar` – Jay Harris Nov 28 '17 at 04:40
  • 2
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – A.D. Nov 28 '17 at 04:45
  • It is not duplicate of scope of variables, I'm just trying to figure out the way to access bar variable. @addy – srinivas Nov 28 '17 at 05:59
  • Thanks for the solution. Would you mind If I ask you to explain what you have done. @JayHarris – srinivas Nov 28 '17 at 06:04
  • convert boo.foo `toString()` then `eval`. Of course, you need to format the string into something that returns `bar`. That's how you ***CAN*** do it. But I don't really recommend it since that is a bad habit. ***EVAL IS ALWAYS EVIL.*** – xGeo Nov 28 '17 at 06:21

1 Answers1

0

You can't access it as you have it in your code. That's how closures work by design. If you want to "see inside" the closure, provide some sort of "getter" function.

Jim Cote
  • 1,746
  • 3
  • 15
  • 26