Getter is a method of getting the value of an attribute, and Setter is a method of setting the value of an attribute. Getter and setter methods can be defined for any predefined core object or user-defined object, adding new properties to existing objects.
There are two ways to define a Getter or Setter method:
1. Define when object initialization
2. After the object is defined, the definition is added through the Object's __defineGetter__ and __defineSetter__ methods.
The only thing to do when defining Getter and Setter methods using the object initialization process is to prefix "get" in the getter method and "set" in the setter method.
Another thing to note is that the getter method has no parameters, and the setter method must have a parameter, that is, the new value of the attribute to be set.
For example:
The code copy is as follows:
o = {
value:9,
get b() {return this.value;},
set setter(x) {this.value = x;}
}
After the object is defined, add a getter or setter method to the object, two special methods __defineGetter__ and __defineSetter__ are used. These two functions require the first to be the name of a getter or setter, given in string, and the second parameter is a function as a getter or setter.
For example, we add a year attribute to the Date object:
The code copy is as follows:
Date.prototype.__defineGetter__('year', function() {return this.getFullYear();});
Date.prototype.__defineSetter__('year', function(y) {this.setFullYear(y)});
var now = new Date;
alert(now.year);
now.year = 2006;
alert(now);
As for which form to adopt mainly depends on the individual's programming style, the first form is compact and easier to understand. But if you want to add Getter or Setter after the object is defined, or the prototype of this object is not written by you or is built-in, then you have to use the second method.
Here is an implementation that adds innerText attribute to Mozilla browser:
The code copy is as follows:
HTMLElement.prototype.__defineGetter__
(
"innerText",function()
//define a getter method to get the value of innerText,
//so you can read it now!
{
var textRange = this.ownerDocument.createRange();
//Using range to retrieve the content of the object
textRange.selectNodeContents(this);
//only get the content of the object node
return textRange.toString();
// give innerText the value of the node content
}