1

Is it possible to get a variable above the current scope in a Javascript object?

var object = {
        access: [{
            actionName: "Defending",
            action: function(unit) {

            }
        }, {
            actionName: "Mining",
            action: function(unit) {
                super.promises.push($interval(function() { // Here I need to access the variable 'promises' from the above scope
                    // do something
                }, 1000));
            }
        }, {
            actionName: "Cutting wood",
            action: function(unit) {
                super.promises.push($interval(function() { // Same here
                    // do something
                }, 1000));
            }
        }],
        promises: []
    };
2
  • You can't (easily) traverse (and maybe not at all) but you can simply use object.promises Commented Nov 10, 2014 at 0:05
  • You would need to use a tree data structure which explicitly tracked the parents of each node. Except for the DOM (which would probably be inappropriate overkill in this case), nothing like you're looking for is provided out-of-the-box in JavaScript. Commented Nov 10, 2014 at 0:07

1 Answer 1

3

You can just do:

var object = {
    access: [{
        actionName: "Defending",
        action: function(unit) {

        }
    }, {
        actionName: "Mining",
        action: function(unit) {
            object.promises.push($interval(function() { // Here I need to access the variable promise from the above scope
                // do something
            }, 1000));
        }
    }, {
        actionName: "Cutting wood",
        action: function(unit) {
            object.promises.push($interval(function() { // Same here
                // do something
            }, 1000));
        }
    }],
    promises: []
};
Sign up to request clarification or add additional context in comments.

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.