是否可以在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: []
};
答案 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: []
};