Objects and Properties
Methods and This
Call an object method that reads another property.
methods-this
When a function is called as an object method, `this` refers to that object for the duration of the call.
Methods and This
methods_this.js
Replay: real traced execution (multi-file project)
const step = 3;
const next = ({
start: 10,
add(n) {
return this.start + n;
}
}).add(step);
console.log("step=" + step);
console.log("next=" + next);
const step = 1;
const next = ({
start: 10,
add(n) {
return this.start + n;
}
}).add(step);
console.log("step=" + step);
console.log("next=" + next);
const step = 5;
const next = ({
start: 10,
add(n) {
return this.start + n;
}
}).add(step);
console.log("step=" + step);
console.log("next=" + next);
step ← 3, next ← 13
1const step→ 3 = 3; //@step=1, 52const next→ 13 = ({3 start: 10,4 add(n) {5 return this.start + n;6 }7}).add(step3);89console.log("step=" + step3);10console.log("next=" + next13);outputstep=3 next=13
step ← 1, next ← 11
1const step→ 1 = 1;2const next→ 11 = ({3 start: 10,4 add(n) {5 return this.start + n;6 }7}).add(step1);89console.log("step=" + step1);10console.log("next=" + next11);outputstep=1 next=11
step ← 5, next ← 15
1const step→ 5 = 5;2const next→ 15 = ({3 start: 10,4 add(n) {5 return this.start + n;6 }7}).add(step5);89console.log("step=" + step5);10console.log("next=" + next15);outputstep=5 next=15
Call the Method
- The object stores
start: 10. stepis3.- Calling
.add(step)runs the method on that object. - Inside the method,
this.startis10. - The returned value is
13.
this.start 10 + step 3 -> 13
Exercise: methods_this.js
Call an object method that uses this.start and prints the next value