I am trying to write a function that prints out a negative value after it’s been run but I keep getting just the number.
const studentHolberton = (() => {
let privateScore = 0;
let name = null;
function changeScoreBy(points) {
privateScore += points;
}
return {
setName: (newName) => {
name = newName;
},
rewardStudent: () => {
changeScoreBy(1);
},
penalizeStudent: () => {
changeScoreBy(-1);
},
getScore: () => {
return `${name}: ${privateScore}`;
},
};
})();
const jerry = Object.create(studentHolberton);
jerry.setName('Jerry');
//reward harry 4times
jerry.rewardStudent();
jerry.rewardStudent();
jerry.rewardStudent();
jerry.rewardStudent();
console.log(jerry.getScore());
const dray = Object.create(studentHolberton);
dray.setName('Dray');
// Reward Draco one time and penalize three times
dray.rewardStudent();
dray.penalizeStudent();
dray.penalizeStudent();
dray.penalizeStudent();
console.log(dray.getScore());
The expected output is
Jerry: 4
Dray: -2
but I am getting
Jerry: 4
Dray: 2
4
Answers
Object.create
creates a new object that uses the argument as the prototype for it.In your particular case, this is pointless because you aren’t storing any data on the object.
All the data is stored in closed over variables so
let privateScore
is shared between both theharry
anddraco
objects.To use the revealing module pattern for this, you’d need to:
Object.create(...)
to create a new instance.You could also take a class based approach to this.
The problem you created only 1 object with IIFE and assigned it to
studentHogwarts
. Then you use it for both students, thus actually using only 1 student.Object::create()
doesn’t change anything, just returning the same object in the both cases.To solve the problem, remove IIFE and call the
studentHorwarst()
to create new students:Your private variables exist in the scope of what is used as a prototype object (first argument of
Object.create
), so both created objects share the same private variables.I would suggest using
class
syntax with private field support.Additionally:
While you can work with
function
s I’d argue its a good idea to do implement this the OOP way withclass
instances that save their individual score. That is what classes are made for.