Consider this code snippet
class A {
constructor() {
this._val = 5;
}
get val() {
return this._val;
}
getVal() {
return this._val;
}
}
const a = new A();
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);
Obtaining _val of object a works via both the accessor get val() as well as the regular method getVal(). Are there any differences between the two other than that the former exposes a property val on a whereas getVal() is function that is exposed as a property on a? Would there be any performance/ coding guideline considerations on when to adopt one over the other?
Take a look at the difference:
class A {
constructor() {
this._val = 5;
}
get val() {
return this._val;
}
getVal() {
return this._val;
}
}
const a = new A();
console.log(a);
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);
class B {
constructor() {
this._val = 6;
}
getVal() {
return this._val;
}
}
const b = new B();
console.log(b);
console.log(`B.val: ${b.val}, B.getVal: ${b.getVal()}`);
You'll notice that get exposes _val directly as a property. The function is a function that accesses _val. That's really the only difference. Use get if you just want the property to be accessible. Use the function is you want to do stuff the variable before making it accessible, like, formatting a date, for example.