I am observing a (for me) not explainable behaviour in my App.
I have a few includes via require(). In one of them, called "addUserFunction.js" I have two functions and an array containing objects.
This is the definition for the objects-array:
exports.itemList = [{itemType:"info",itemName:"Information"},{...},{...}];
This is the definition for the two functions:
exports.getItem = function(data) {
var returnItem = {};
for (var i=0;i<exports.itemList.length;i++) {
if (exports.itemList[i].itemType == data.itemType){
returnItem = exports.itemList[i]; // This line seems to pass a reference, not assign/copy
}
}
returnItem.itemName = (data.itemName) ? data.itemName : returnItem.itemName;
return returnItem;
}
exports.createPlan = function(formValues) {
var returnItem = {
id: 0,
description: 'foobar',
items: [
exports.getItem({itemType:'info',itemName:'Information'}),
exports.getItem({itemType:'somethingelse'}),
exports.getItem({itemType:'bla',itemName:'yougottheidea'})
]
};
return returnItem;
}
Now the problem is: as soon as I use the function exports.getItem
and overwrite some of the properties, getItem
seems to link the newly created returnItem
with the original itemList[i]
. So the next call of itemList[i]
uses the property values of the first call. Hope that was explained understandable.
How can this be?
createPlan()
is called from another required()
file like this:
var aF = require('addUserFunctions');
function addUser() {
var formValues = {name: 'test'};
formValues.foo = aF.createPlan(formValues);
}
module.exports = addUser;