无法将多个 nodejs 导出 return 值分配给变量

Trouble assigning multiple nodejs exports return values to variables

我有两个文件,一个主文件和一个模块文件。在模块文件中,我导出了两个函数,它们是 return 个对象。在主文件中,我将变量设置为每个方法的 return 值。但是,每个变量都设置为调用的 last 方法的 return 值。我在这里做错了什么?

/* 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;
};

注意:使用真实代码编辑,而非示例代码

当你这样做时:

thisArmor = baseStats;

不是复制"baseStats"对象。由于模块中的两种方法都会修改 return 对同一对象的引用,因此您会得到观察到的效果。

有几种方法可以实现Node的浅拷贝操作; see this Whosebug question。使用其中一种方法,您将从 "baseStats".

的本地副本开始这些方法