Author: anbutu
Source: http://anbutu.javaeye.com/blog/post/194276
Keywords: JavaScript Mozilla __defineGetter__ __defineSetter__
Getter is a method to get the value of an attribute ,Setter is a method of setting the value of a property. 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 the Getter or Setter method:
Define when the object is initialized
After the object is defined, append the definition through the __defineGetter__ and __defineSetter__ methods of Object
When using the object The only thing you have to do during the initialization process to define the 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:
o = { 🎜> value:9,
get b() {return this.value;},
set setter(x) {this.value = x;}
}
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 the first to be the name of the getter or setter, given as a string, and the second parameter to be the function that is the getter or setter.
For example, we add a year attribute to the Date object:
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);
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:
HTMLElement.prototype.__defineGetter__ can read it now! Contents(this);
/ /only get the content of the object node
Return texturing.tostring ();
// give innertext the value of the node content
}
);