Objects and Properties
Methods and This
Call an object method that reads another property.
Methods and This
methods_this.js
const step = 3;
const next = ({
start: 10,
add(n) {
return this.start + n;
}
}).add(step);
console.log("step=" + step);
console.log("next=" + next);
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
methods-this
When a function is called as an object method, `this` refers to that object for the duration of the call.
Exercise: methods_this.js
Call an object method that uses this.start and prints the next value