我有两个文件,一个主文件和一个模块文件。在模块文件中,我导出了两个返回对象的函数。在主文件中,我将变量设置为每个方法的返回值。但是,每个变量都设置为调用的 last 方法的返回值。我在这里做错了什么?
/* main file */
module.exports = function(robot) {
var startingCharacter = require('./data/starting/character.json'),
make = require('./includes/make.js');
return robot.respond(/dungeon me/i, function(msg) {
var character = startingCharacter,
weapon = make.weapon(0),
armor = make.armor(0);
console.log(weapon); // <- returns value from make.armor(0)
console.log(armor); // <- returns value from make.armor(0)
}
};
/* module file */
var random = require('./random.js');
var baseStats = {
'equipped': 'true',
'attack': '0',
'damage': '0',
'defense': '0',
'health': '0',
'luck': '0',
'passivePower': {},
'activePower': {}
};
// Generate a weapon
exports.weapon = function(level) {
var weaponNames = require('../data/nouns/weapon_names.json');
var thisWeapon = {};
if (level === 0) {
var adjNeg = require('../data/adjectives/negative.json');
thisWeapon = baseStats;
thisWeapon.name = adjNeg[random(0, adjNeg.length)] + ' ' + weaponNames[random(0, weaponNames.length)];
thisWeapon.type = 'weapon';
}
console.log(thisWeapon); // <- returns correct value
return thisWeapon;
};
// Generate armor
exports.armor = function(level) {
var armorNames = require('../data/nouns/armor_names.json');
var thisArmor = {};
if (level === 0) {
var adjNeg = require('../data/adjectives/negative.json'),
animals = require('../data/nouns/animals.json');
var armorName = armorNames[random(0, armorNames.length)];
thisArmor = baseStats;
if (armorName === 'Hide') {
thisArmor.name = animals[random(0, animals.length)] + ' ' + armorName + ' armor';
}
else {
thisArmor.name = adjNeg[random(0, adjNeg.length)] + ' ' + armorName;
}
thisArmor.type = 'armor';
}
console.log(thisArmor); // <- returns correct value
return thisArmor;
};
注意:使用实际代码编辑,而不是示例代码
答案 0 :(得分:1)
执行此操作时:
thisArmor = baseStats;
你不制作“baseStats”对象的副本。由于模块中的两个方法都修改并返回对同一对象的引用,因此可以获得您观察到的效果。
有几种方法可以为Node实现浅拷贝操作; see this Stackoverflow question。使用其中一种方法,您可以使用“baseStats”的本地副本启动这些方法。