Javascript 获取子函数中父字段的名称
我需要在子函数中获取父元素(CentralS)的名称,如何才能做到这一点? 徖 我的解决方案Javascript 获取子函数中父字段的名称,javascript,Javascript,我需要在子函数中获取父元素(CentralS)的名称,如何才能做到这一点? 徖 我的解决方案 const roles = { CentralS: { 'harvester': { 'quantity': 3, 'strength': [WORK, CARRY, CARRY, MOVE, MOVE] } } } for (const spawnName in roles) { for (const roleName i
const roles = {
CentralS: {
'harvester': {
'quantity': 3,
'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
}
}
}
for (const spawnName in roles) {
for (const roleName in roles[spawnName]) {
if (roles[spawnName].hasOwnProperty(roleName)) {
roles[spawnName][roleName].currentQuantity = _.sum(Game.creeps, (c) => {
console.log(spawnName) // CentralS
return c.memory.role === roleName && c.memory.spawnName === spawnName;
})
}
}
}
您可以尝试在该对象的主体之外定义
currentQuantity
属性,如下所示:
const roles = {
CentralS: {
'harvester': {
'quantity': 3,
'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
}
}
};
roles.CentralS.harvester.currentQuantity = _.sum(Game.creeps, (c) => {
if (c.memory.role === 'harvester') {
// console.log(c.memory.spawnName)
console.log(Object.keys(this))
console.log(this)
console.log(roles.CentralS);
}
return c.memory.role === 'harvester';
});
这是不可能的。对象没有任何指向包含对它们的引用的对象的链接。对象没有任何“父”属性,除非您手动附加此类属性。那么我必须手动在该对象的每个函数中写入Central、CentralS1、CentralS2?我不能以某种方式获得这个通用对象的名称吗?是的,好主意,我使用了cycle并获得了我想要的(角色中的const-spawnName){for(角色中的const-roleName[spawnName]){roles[spawnName].roleName.currentQuantity=\ sum(Game.crews,(c)=>{console.log(spawnName)//CentralS返回c.memory.role===roleName;})}
const roles = {
CentralS: {
'harvester': {
'quantity': 3,
'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
}
}
};
roles.CentralS.harvester.currentQuantity = _.sum(Game.creeps, (c) => {
if (c.memory.role === 'harvester') {
// console.log(c.memory.spawnName)
console.log(Object.keys(this))
console.log(this)
console.log(roles.CentralS);
}
return c.memory.role === 'harvester';
});