如何在Javascript对象中访问父作用域?

时间:2014-11-09 23:59:31

标签: javascript

是否可以在Javascript对象中获取高于当前范围的变量?

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

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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