Encountered an unusual issue that can be best described through code:
var fruits = ["apples", "oranges", "pears"];
var Breakfast = {
_consume : function (fruit) {
Breakfast[fruit]._numConsumed++;
}
};
for (var f in fruits) {
var fruit = fruits[f];
Breakfast[fruit] = {
consume : function () {
Breakfast._consume(fruit);
},
_numConsumed: 0
}
}
Breakfast.pears.consume();
Breakfast.pears.consume();
Breakfast.apples.consume();
Breakfast.apples.consume();
Breakfast.apples.consume();
console.log("Pears eaten: " + Breakfast.pears._numConsumed);
console.log("Apples eaten: " + Breakfast.apples._numConsumed);
This results in:
$ node example.js
Pears eaten: 5
Apples eaten: 0
Not sure how to address this behavior?
Is there a mistake in my code? Or should I follow a different approach? (considering that I want the "consume" function to work for all fruits)
Thank you!