javascriptgetter

Why bother with getter functions that just read public properties?


I've peeked into many plugins' code (for educational purposes) and basically every one of them (which deals with prototypes), has bunch of functions like this:

myMarker.prototype.getPosition = function () {
    return this.latlng; 
};

//OR

myMarker.prototype.getObject = function () {
    return this;
};

What's the reason behind this?

Why not just to use someObject.latlng instead of someObject.getPosition()?


Solution

  • One common reason for doing this is to avoid coupling the object's internal data storage to the API; in this example you could change the way the position is stored internally, and then add some processing to getPosition() to return a backwards compatible result.

    For example, version 1.1 of this library might look like this, and calling code wouldn't need to be changed:

    myMarker.prototype.getPosition = function() {
        return [this.latitude, this.longitude]; 
    };
    

    It is possible to accomplish this using computed properties with ES5 get and set, but only if the code doesn't need to run on Internet Explorer 8 and below.