1
function A() {
  this.foo = function() {
    return "bar";
  };
}

A.prototype.foo = function() {
  return "bar";
};

I mostly go by the second approach for adding "instance methods". Mostly because of habit and it's a little memory saver. But when is it appropriate to use the first approach?

NOTE: This question has almost been asked before but they mostly talk about the different and this question is more when to use each.

SandeliusME
  • 802
  • 1
  • 10
  • 19
  • These are not alternatives, but two completely different things. The first example is what you would call "instance methods". The second is more like a "static" method, but not really. http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – Tudmotu Oct 12 '14 at 21:15

1 Answers1

3

You can use the approach with this for private variables.

Example:

function Counter() {
    var c = 0;

    this.getCount = function() {
        return c;
    };

    this.increase = function() {
        c++;
    };
}

There would be no way to give functions access to the variable through the prototype approach without exposing it to everyone else as well.

Overv
  • 8,433
  • 2
  • 40
  • 70
  • Instance specific private variables. You can have private variables on the prototype: http://stackoverflow.com/a/21800194/1641941 – HMR Oct 12 '14 at 23:29
  • So that's is really the only reson to use this functions inside the constructor then? – SandeliusME Oct 13 '14 at 05:51