Classes and Methods
Method Updates
Update an instance field inside a method.
method-update
Methods can update fields through `this`. Keep the update small and return the new value when callers need it immediately.
Method Updates
method_update.js
Replay: real traced execution (multi-file project)
const start = 10;
class Score {
constructor(start) {
this.value = start;
}
add(points) {
this.value = this.value + points;
return this.value;
}
}
const next = new Score(start).add(5);
console.log("start=" + start);
console.log("next=" + next);
const start = 3;
class Score {
constructor(start) {
this.value = start;
}
add(points) {
this.value = this.value + points;
return this.value;
}
}
const next = new Score(start).add(5);
console.log("start=" + start);
console.log("next=" + next);
const start = 20;
class Score {
constructor(start) {
this.value = start;
}
add(points) {
this.value = this.value + points;
return this.value;
}
}
const next = new Score(start).add(5);
console.log("start=" + start);
console.log("next=" + next);
start ← 10, this.value ← 10
1const start→ 10 = 10; //@start=3, 202class Score {3 constructor(start) {4 this.value = start10;5 }67 add(points) {8 this.value = this.value + points;9 return this.value;10 }11}1213const next = new Score(start10).add(5);values this step10this.valuethis.value ← 15
4 this.value = start;5}67add(points5) {8 this.value = this.value→ 15 + points5;9 return this.value15;10}next ← 15
10 }11}1213const next→ 15 = new Score(start10).add(5);1415console.log("start=" + start10);16console.log("next=" + next15);outputstart=10 next=15
start ← 3, this.value ← 3
1const start→ 3 = 3;2class Score {3 constructor(start) {4 this.value = start3;5 }67 add(points) {8 this.value = this.value + points;9 return this.value;10 }11}1213const next = new Score(start3).add(5);values this step3this.valuethis.value ← 8
4 this.value = start;5}67add(points5) {8 this.value = this.value→ 8 + points5;9 return this.value8;10}next ← 8
10 }11}1213const next→ 8 = new Score(start3).add(5);1415console.log("start=" + start3);16console.log("next=" + next8);outputstart=3 next=8
start ← 20, this.value ← 20
1const start→ 20 = 20;2class Score {3 constructor(start) {4 this.value = start20;5 }67 add(points) {8 this.value = this.value + points;9 return this.value;10 }11}1213const next = new Score(start20).add(5);values this step20this.valuethis.value ← 25
4 this.value = start;5}67add(points5) {8 this.value = this.value→ 25 + points5;9 return this.value25;10}next ← 25
10 }11}1213const next→ 25 = new Score(start20).add(5);1415console.log("start=" + start20);16console.log("next=" + next25);outputstart=20 next=25