Getter is a way to get the value of a property, a setter is a way to set the value of a property. You can define getter and setter methods for any of the predefined core objects or user-defined objects to add new properties to existing objects.
There are two ways to define the getter or setter method:
1. Defining when object initialization
2. Append definition to object after definition by __definegetter__, __definesetter__ method
The only thing to do when using the object initialization process to define the getter and setter methods is to precede the Getter method with "get" and precede the setter method with "set."
One thing to note is that the Getter method has no parameters, and the setter method must have a parameter, which is the new value of the property to set.
For example:
Copy Code code as follows:
o = {
Value:9,
Get B () {return this.value;},
Set Setter (x) {this.value = x;}
}
Adding getter or Setter methods to an object after the object is defined is __definegetter__ and __definesetter__ through two special methods. These two functions require that the first is the name of the getter or setter, given in string, and that the second parameter is a function as a getter or setter.
For example, we add a year attribute to the Date object:
Copy Code code 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 to which form depends primarily on the individual's programming style, the first form of the structure is compact and easier to understand. But if you want to add the getter or setter after the object definition, or if the object's prototype is not written by you or a built-in object, then you have to use the second way.
Here is an implementation that adds the InnerText property to the Mozilla browser:
Copy Code code as follows:
htmlelement.prototype.__definegetter__
(
"InnerText", function ()
Define a getter to get the value of innertext,
So 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
}