Home > Article > Web Front-end > Introduction to __defineGetter__ and __defineSetter__ in javascript_javascript skills
Getter is a method to get the value of an attribute, and Setter is a method to set the value of an attribute. You can define getter and setter methods for any predefined core object or user-defined object, thereby adding new properties to existing objects.
There are two ways to define a Getter or Setter method:
1. Define
during object initialization
2. After the object is defined, add definitions through Object’s __defineGetter__ and __defineSetter__ methods
The only thing to do when using the object initialization process to define Getter and Setter methods is to add "get" in front of the getter method and "set" in front of the setter method.
Another thing to note is that the getter method has no parameters, and the setter method must have one parameter, which is the new value of the attribute to be set.
For example:
After the object is defined, adding a getter or setter method to the object requires two special methods __defineGetter__ and __defineSetter__. These two functions require that the first parameter be the name of the getter or setter, given as a string, and that the second parameter be the function that is the getter or setter.
For example, we add a year attribute to the Date object:
Which form to use mainly depends on your personal programming style. The first form is compact and easier to understand. But if you want to add a Getter or Setter after the object is defined, or the prototype of this object is not written by you or is a built-in object, then you have to use the second method.
The following is an implementation of adding the innerText attribute to the Mozilla browser: