简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM