0

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()?

Solo
  • 6,687
  • 7
  • 35
  • 67
  • 2
    this.latlng may be a private property of the object so that you are restricted to change this property. – Manish Jangir Feb 01 '16 at 05:49
  • @ManishJangirBlogaddition.com: There is no such thing like a "private property" in JavaScript. – Bergi Feb 01 '16 at 05:54
  • Why don't you ask the developers who invented it? If they say `latlng` is unreadable, slap their faces off. – choz Feb 01 '16 at 05:57
  • Perhaps one may want to restrict access to the object variables and allow access only via getter setter methods?Check this [link](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – Satej S Feb 01 '16 at 05:57

2 Answers2

3

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.

Daisy Leigh Brenecki
  • 7,571
  • 6
  • 28
  • 43
0

When you say like this.

myMarker.prototype.getPosition = function() {

    return this.latlng; 
};

You are defining function getPosition which available to all instance to class myMarker.

So,all object of this class share this method without replication.

For someObject.latlng,there is nothing wrong. But assume, this object is accessible to all which are in the current scope.So,it can be modified/accessible to anyone.

When you go through prototype you are trying to define some pattern,which gives restriction for access and modification of property

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53