So I have a class XYZ in JavaScript, it has few functions:
class XYZ{
constructor(){
this.text=null;
}
f1(){
// Do Something
return this;
}
f2(){
// Do Something
return this;
}
f3(txt=null){
if(txt){
this.text=txt;
this.show();
}
// Do Something
return this;
}
show(){
console.log(this.text)
}
}
const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3().f2();
What I want to achieve is that if there is no text to pass to f3, I want to skip the brackets and use it like a getter:
const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3.f2();
I can achieve something similar like this using getter and setter, but I don't want to break the chain calling. Is there a way where we can skip braces if not passing a value, or using the same name getter and method together? Thanks
You can use
Proxyto redirect getters invoked on methods back to the instance with anotherProxy. If a method's getter is invoked (likef1.f2) - call the method (f1):