What are __defineGetter__() and __defineSetter__() functions?
To answer your question __defineGetter__()
and __defineSetter__()
are the old/original way to create a getter and a setter for an object's property. They allow you use an object's property as a name/value pair while behind the scenes these name/value pairs are supported by functions.
For example, let's say you wanted to reference some random numbers in fixed ranges. You could express these as words with the maximum of the range and it would look like a property.
var random = {};
random.__defineGetter__('ten', function() {
return Math.floor(Math.random()*10); });
random.__defineGetter__('hundred', function() {
return Math.floor(Math.random()*100); });
Note that the while the above example answers the question you should not use this solution. Instead you should use the modern form of getters and setters since ES5:
var random = {
get ten() { return Math.floor(Math.random()*10); },
get hundred() { return Math.floor(Math.random()*100); }
};
Either of the above constructs would allow you to get a random number like this:
var myrand = random.ten;
// returns a result in the range 0 to 9
See the MDN docs here for a description and example code:
A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties.
As noted in the docs (and by @ cwallenpoole), __define[GS]etter__()
functions are now deprecated. There's a lot more detail in this article. I believe the defineProperty() function is now the preferred syntax.