Example Getter and Setter methods in Javascript

The set method sets a property to an object. It is used by placing the reserved name "set" before the name of the method and uses only one parameter, which will be the one that designates the value of the object.
The set method can also be used inside a class by assigning a value to the property set inside the instantiated object.
The get method retrieves the value of an object's property. It is used by prepending the reserved name "get" before the method name and does not use parameters.
The get method can be used inside a class, collecting the value of a property inside the instantiated object.

The following example shows a person class with name and age properties. This class sets setter and getter classes for each of the properties.
Once the person class is established, we instantiate it to a person1 object with default properties "Paul, 35", collect the values with the get methods, and set new values to the person1 object with the set methods.

Comments

PHP Captcha


Interesting Articles