0

I have a function foo which holds the bar. Is it possible to access bar from an external function with the code in its current state (ie - not changing anything inside foo).

From my understanding, this is not possible as bar is only visible for foo. My solution would be to create a get() that would extract bar.

var foo = function() {
    var bar = {
        a : 'a',
        b : 'b'
    };
};
0

5 Answers 5

1

It is not possible to access bar without returning it. You'll need to scope it above foo:

var bar = {
    a : 'a',
    b : 'b'
};
var foo = function() {
  // do stuff with bar
};

or have foo return bar

var foo = function() {
    var bar = {
        a : 'a',
        b : 'b'
    };
    return bar;
};
var otherBar = foo();
Sign up to request clarification or add additional context in comments.

Comments

1

No. bar is effectively privately scoped in your above example. If you want to access bar, you will have to provide an accessor, like you suggest, e.g. getBar().

Comments

1

bar is a local object only visible from within foo function scope, so you are correct. bar is not accessible from outside unless your foo function returns a function to access it, so your choice to implement a getter sounds about approriate.

Best.

Comments

1

You are correct, in its current form, the only way to access the bar variable would be through an accessor method. But depending on how you wish to implement this code, you can declare the bar variable as a property of the foo object.

It would look something like this:

var foo = function() {
  this.bar = {
    a: 'a',
    b: 'b'
  }
}

var baz = new foo();

baz.bar.a; //returns 'a'

Comments

1

As others said, you cant, but if all ways count :) ,you can get bar this way:

<script type="text/javascript">
    var foo = function () {
        var bar = {
            a: 'a',
            b: 'b'
        };
    };

    var haha = function () {
        var evalBar = foo.toString().match("var bar[^}]*};")[0];
        eval(evalBar);
        console.log(bar);
    }

    haha();
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.