Classes and Methods
Method Chains
Create an instance and use its method result immediately.
method-chain
For short-lived objects, creating an instance and using its method result in the next expression keeps the code compact while still showing the class behavior.
Method Chains
method_chain.js
Replay: real traced execution (multi-file project)
const text = "trace";
class TextTool {
constructor(text) {
this.text = text;
}
upper() {
return this.text.toUpperCase();
}
}
const output = new TextTool(text).upper();
console.log("text=" + text);
console.log("output=" + output);
const text = "replay";
class TextTool {
constructor(text) {
this.text = text;
}
upper() {
return this.text.toUpperCase();
}
}
const output = new TextTool(text).upper();
console.log("text=" + text);
console.log("output=" + output);
const text = "class";
class TextTool {
constructor(text) {
this.text = text;
}
upper() {
return this.text.toUpperCase();
}
}
const output = new TextTool(text).upper();
console.log("text=" + text);
console.log("output=" + output);
text ← trace, this.text ← trace
1const text→ trace = "trace"; //@text="replay", "class"2class TextTool {3 constructor(text) {4 this.text = texttrace;5 }67 upper() {8 return this.text.toUpperCase();9 }10}1112const output = new TextTool(texttrace).upper();values this steptracethis.textupper()
4 this.text = text;5}67upper() {8 return this.texttrace.toUpperCase();9}output ← TRACE
9 }10}1112const output→ TRACE = new TextTool(texttrace).upper();1314console.log("text=" + texttrace);15console.log("output=" + outputTRACE);outputtext=trace output=TRACE
text ← replay, this.text ← replay
1const text→ replay = "replay";2class TextTool {3 constructor(text) {4 this.text = textreplay;5 }67 upper() {8 return this.text.toUpperCase();9 }10}1112const output = new TextTool(textreplay).upper();values this stepreplaythis.textupper()
4 this.text = text;5}67upper() {8 return this.textreplay.toUpperCase();9}output ← REPLAY
9 }10}1112const output→ REPLAY = new TextTool(textreplay).upper();1314console.log("text=" + textreplay);15console.log("output=" + outputREPLAY);outputtext=replay output=REPLAY
text ← class, this.text ← class
1const text→ class = "class";2class TextTool {3 constructor(text) {4 this.text = textclass;5 }67 upper() {8 return this.text.toUpperCase();9 }10}1112const output = new TextTool(textclass).upper();values this stepclassthis.textupper()
4 this.text = text;5}67upper() {8 return this.textclass.toUpperCase();9}output ← CLASS
9 }10}1112const output→ CLASS = new TextTool(textclass).upper();1314console.log("text=" + textclass);15console.log("output=" + outputCLASS);outputtext=class output=CLASS