2

How would I access a parents functions "var" variables in the following scenario (I can only edit the definition of the reset function):

_.bind(function(){
    var foo = 5;

    var reset = function(){
        foo = 6;  //this changes foo,
        bar = 7;  //**I want this to add another "var", so I don't pollute global scope
    }
    reset();
    console.log(foo); //6
    console.log(bar); //7
}, window);

4 Answers 4

1

Sorry, but you can't.

The only way you can access namespaces is the with statement.

For example, if you were able to re-write the whole thing, it could be done like this:

_.bind(function(){
    var parentNamespace = {
        foo: 5,
    };

    with (parentNamespace) {
        var reset = function(){
            foo = 6;  //this changes foo,
            parentNamespace.bar = 7;  //**I want this to add another "var", so I don't pollute global scope
        }
        reset();
        console.log(foo); //6
        console.log(bar); //7
    }
}, window);

But this is most likely almost certainly a bad idea.

Sign up to request clarification or add additional context in comments.

2 Comments

and with only add a obj to scrope
And with is a scary statement in JavaScript for a good reason.
1

Would this work for you?

_.bind(function(){
    var foo = 5, bar;

    var reset = function(){
        foo = 6;  //this changes foo,
        bar = 7;  //**I want this to add another "var", so I don't pollute global scope
    }
    reset();
    console.log(foo); //6
    console.log(bar); //7
}, window);

2 Comments

This is a good way to do it. If you want to make a veritable accessible to the enclosing scope you have to declare it in th enclosing scope
Yeah, this is the way I have it now, I was just frustrated by the duplication of all the names.
0

I'm not sure I understand your question, so my answer might not be what you want.

var reset = function(){
    foo = 6;  
    reset.bar = 7;   
}
reset.bar = 13;
reset();  // reset.bar is back to 7.

Comments

0

ECMA-262 excplicitly prevents access to a function's variable object (functions don't actually have to have one, they just have to behave as if they do), so you can't access it.

You can only add properties by declaring variables in an appropriate scope or including them in the formal parameter list of a FunctionDeclaration or FunctionExpression, there is no other means.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.