Getters are convenient methods to get the value of specific properties; as the name suggests, setters are methods that set the value of a property. Often, you may want to derive a value based on some other values. Traditionally, getters and setters used to be functions such as the following:
var person = { firstname: "Albert", lastname: "Einstein", setLastName: function(_lastname){ this.lastname= _lastname; }, setFirstName: function (_firstname){ this.firstname= _firstname; }, getFullName: function (){ return this.firstname + ' '+ this.lastname; } }; person.setLastName('Newton'); person.setFirstName('Issac'); console.log(person.getFullName());
As you can see, setLastName()
, setFirstName()
, and getFullName()
are functions used to do get and set of properties. Fullname
is a derived property by concatenating the firstname
and lastname
properties. This is a very common use case and ECMAScript 5 now provides you with a default syntax for getters...