Elfayer
Elfayer

Reputation: 4561

How to access parent scope inside Javascript object?

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: []
    };

Upvotes: 1

Views: 265

Answers (1)

mattr
mattr

Reputation: 5518

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: []
};

Upvotes: 3

Related Questions