0

So I'm just beginning with JS, and I couldn't seem to find an answer to this simple and possibly stupid question. Why should I do this:

function Cat() {}

Cat.prototype.meow = function() {
    ...
}

instead of this:

function cat_meow() {
    ...
}

function Cat() {
    this.meow = cat_meow;
}

Because in the second snippet I still only define the function once, so what's the problem with using that instead of prototype?

EDIT: This question is not quite the same as the one linked as a duplicate. Please reread my question.

name
  • 362
  • 2
  • 12
  • 3
    Related: [*Use of 'prototype' vs. 'this' in JavaScript?*](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) – Wiktor Stribiżew Feb 12 '16 at 23:29
  • @WiktorStribiżew I think you commented too quick because my example is different. I don't define the function inside the constructor. – name Feb 12 '16 at 23:30
  • Hello??? Who is marking my question as a duplicate? It's not even the same! – name Feb 12 '16 at 23:31
  • Am I going to have to re-ask this question? – name Feb 12 '16 at 23:32
  • Hint: suppose you have two or more instances of each and then you want to **redefine** the function. Is it equally easy? – Wiktor Zychla Feb 12 '16 at 23:32
  • 2
    The accepted answer to that question describes exactly what is the difference (and therefore the potential problem) of assigning methods using `this` instead of the prototype. You are right that you save some resources by declaring the function outside of the constructor, but there is a big difference, because the function is not aware of the object that calls it. – GolezTrol Feb 12 '16 at 23:33
  • @GolezTrol Thank you for elaborating – name Feb 12 '16 at 23:35

0 Answers0