getter setter (JS)

ref – https://javascriptplayground.com/es5-getters-setters/

this is ugly:

But this is ugly, and requires the users of your object to care that the properties are related; in a more complex example, that might not be as obvious as with names. Luckily, there’s a better way, added in ECMAScript 5.

we see that we have a get/set for property fullName.

Following them is the property they relate to (fullName) and a function body that defines the behavior when the property is accessed (name = person.fullName) or modified (person.fullName = ‘Some Name’).

In other words, get simply means to access the data, so we naturally return the property data. set means to set some properties in the object through one parameter. We can only provide one parameter because in an assignment, there’s only one parameter on the right side.

These two keywords define accessor functions: a getter and a setter for the fullName property.

When the property is accessed, the return value from the getter is used.

When a value is set, the setter is called and passed the value that was set. It’s up to you what you do with that value, but what is returned from the setter is the value that was passed in – so you don’t need to return anything.

The official way: Object.defineProperty

This method takes three arguments.

1) The first is the object to add the property to

2) the second is the name of the property

3) and the third is an object that describes the property (known as the property’s descriptor).

But why do it this way?

The advantage here isn’t immediately apparent. Other than being able to add properties after creating the initial object, is there a real benefit?

When you define a property this way, you can do much more than just define a setter or getter. You may also pass following keys:

configurable (false by default): if this is true, the property’s configuration will be modifiable in future.
enumerable (false by default): if true, the property will appear when looping over the object (for (var key in obj)).

We can also define properties that don’t have explicit getters or setters:

This will create person.age, and set it to the value 42. It’s important to note that this property isn’t writable. Calling person.age = 99 will have no effect. In this way you can create read-only properties. If a property has a value key set, it cannot have a getter or setter. Properties can have values or accessors, not both.

Not only that, but because the enumerable property defaults to false, this property will not appear when we loop over the object’s keys.

If we wanted to make a property writable, we would need to set the writable property:

Example 1


output:

10
7.071067811865475
7.071067811865475

Example 2

Example 3