我有兩個文件,一個主文件和一個模塊文件。在模塊文件中,我導出兩個函數,它們返回對象。在主文件中,我將變量設置爲每個方法的返回值。但是,每個變量都設置爲最後的方法的返回值。我在這裏做錯了什麼?分配多個nodejs的麻煩導出返回值到變量
/* 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;
};
注:與真正的代碼編輯,而不是示例代碼,
發佈的代碼有錯誤 - 這裏寫的「method2」代碼*聲明*「myObject1」,但使用*「myObject2」。當這個問題得到解決後,代碼工作正常。 – Pointy 2015-04-05 20:32:52
尖尖 - 你說得對。我編寫了示例代碼,認爲人們更容易看,我犯了一個錯誤,並修復它的工作。我將用我正在使用的實際代碼替換示例代碼,它具有我描述的行爲。 – bronzehedwick 2015-04-05 20:54:30
好的,謝謝。這當然有幫助。 – Pointy 2015-04-05 21:07:24