I'm trying to understand what the advantage is, if any, of the following:
const obj = {
forename: 'Foo',
surname: 'Bar',
get name() {
//yes I get that I can do other stuff here
return this.forename+' '+this.surname;
}
}
alert(obj.name); //Foo Bar
...over...
const obj = {
forename: 'Foo',
surname: 'Bar',
name() {
return this.forename+' '+this.surname;
}
}
alert(obj.name()); //Foo Bar
I've read around (1; 2; 3) but can't seem to see any benefit beyond readability and code style. Is that all it is? No implicit behavioural changes between the two methods?
Is it with one eye on future class property/method visibility in JavaScript? That would make sense - getters for private properties. But since that's not here yet, I can't see the point of the above.
Can anyone enlighten me?
They are code constructs that help developers access the properties of objects in a secure way. With getters, you can access (“get”) the values of properties from external code, while setters let you change (“set”) their values. In this tutorial, we'll show you how you can create getters and setters in JavaScript.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
Getters and setters allow you to define Object Accessors (Computed Properties).
So I am confused, are getter and setter necessary in JavaScript? Yes, they are necessary sometimes. If you don't need them in your code, just don't use them. For perspective, this question is answered for Java in this question.
One difference is typeof
will actually work as expected when using a getter, that is, it will return the actual type of the primitive returned by the getter, while using a method will always return function
:
const objGetter = {
forename: 'Foo',
surname: 'Bar',
get name() {
return `${ this.forename } ${ this.surname }`;
}
}
const objGetterLogic = {
forename: undefined,
surname: 'Bar',
get name() {
return this.forename ? this.surname : 3;
}
}
const objMethod = {
forename: 'Foo',
surname: 'Bar',
name() {
return `${ this.forename } ${ this.surname }`;
}
}
console.log(`objGetter`, typeof objGetter.name);
console.log(`objMethod`, typeof objMethod.name);
console.log(`objGetterLogic (without forename)`, typeof objGetterLogic.name);
objGetterLogic.forename = 'Alice';
console.log(`objGetterLogic (with forename)`, typeof objGetterLogic.name);
Of course, you can call name()
in the version with the method, but with the getter that will work transparently.
Also, if you have nested getters, you can call them transparently, which is something that comes in handy if you are navigating an object programmatically, as otherwise, you would need to account for the possibility of properties being either a value or a function
that needs to be called to get the actual value you need:
class Shape {
constructor(type, children) {
this.type = type || '';
this.children = children || [];
}
get firstChild() {
return this.children[0];
}
get lastChild() {
return this.children[this.children.length - 1];
}
}
const group1 = new Shape('group1', [
new Shape('a'),
new Shape('b'),
new Shape('c'),
]);
const group2 = new Shape('group2', [
new Shape('d'),
new Shape('e'),
new Shape('f'),
]);
const group4 = new Shape('group4', [
group1,
group2,
]);
console.log(group4.firstChild.lastChild.type);
In any case, I think one of the greatest advantages of getters and setters are just increased readability and reduced verbosity, even though that usually comes down to personal preference anyway. In any case, I rather use:
person.name = 'Alice Smith';
Than:
person.setName('Alice', 'Smith');
But we could also argue the latter might be more appropriate in some cases.
Since you defined just a getter for name
, without defining a setter, if you attempt to change its value, for example obj.name = "foo"
, nothing is going to happen.
On the other hand, if you try to change your name
property on your second object, nothing will stop you by doing so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With