Reputation: 7982
I have the following piece of code below:
class Set {
constructor() {
console.log("New Set!");
}
get repsCompleted() {
return this._repsCompleted;
}
set repsCompleted(value) {
this._repsCompleted = value;
}
}
class Exercise {
constructor(name) {
console.log(name);
this.name = name;
}
get sets() {
return [new Set(), new Set(), new Set()]
}
}
let barbellSquat = new Exercise("Barbell Squat");
let updatedBarbellSquat = updateRepsCompleted(barbellSquat);
console.log(updatedBarbellSquat);
function updateRepsCompleted(exercise) {
for (var i = 0; i < exercise.sets.length; i++) {
exercise.sets[i].repsCompleted = 5;
}
return exercise;
}
I have a class exercises, which has a property sets, which is an array of objects of type Set.
So I create a new object off the Exercise class then pass the object to a function, whose purpose is to update the set objects and set the property "repsCompleted" to 5.
Then I console.log the exercise object, only to find that repsCompleted is undefined. I can't figure out why.
Here's a fiddle with the code:
https://jsfiddle.net/the_archer/a09tpr63/10/
Upvotes: 0
Views: 445
Reputation: 781255
You shouldn't use a getter for sets
. A getter or setter is used every time the corresponding property is read or assigned, to allow you to customize the way that property works. The getter isn't only used the first time the property is accesssed.
So every time you use exercise.sets
it creates a new array containing 3 empty Set
objects. sets
should be an ordinary property so you can retrieve the same value every time. You can initialize it in the constructor.
If you want to hide the sets
property, like you did with repsCompleted
in the Set
class, you can use the same method: use a different name for the actual property, and define a getter and setter that accesses it. You can also initialize it lazily by checking whether the property is set yet.
class Set {
constructor() {
console.log("New Set!");
}
get repsCompleted() {
return this._repsCompleted;
}
set repsCompleted(value) {
this._repsCompleted = value;
}
}
class Exercise{
constructor(name) {
this.name = name;
this._sets = null;
}
get sets() {
if (!this._sets) {
this._sets = [new Set(), new Set(), new Set()];
}
return this._sets;
}
set sets(value) {
this._sets = value;
}
}
let barbellSquat = new Exercise("Barbell Squat");
let updatedBarbellSquat = updateRepsCompleted(barbellSquat);
console.log(updatedBarbellSquat);
function updateRepsCompleted(exercise) {
for (var i = 0; i < exercise.sets.length; i++) {
exercise.sets[i].repsCompleted = 5;
}
return exercise;
}
Upvotes: 1