1

Is there any difference when we declare our methods within a class

class Foo {
   ...
   doSomething(){
     ...
   }
}

or directly to the class prototype?

class Foo {
    ...
}

Foo.prototype.doSomething = function(){
    ...
}
José Salgado
  • 981
  • 10
  • 25

3 Answers3

2

The major difference is that one style is readable and the other is not :-) For all normal purposes, they behave the same.

However, they do differ in details:

  • the assigned method is anonymous, the defined method has a .name
  • the assigned function has a .prototype and is constructible, the defined method doesn't
  • the assigned method is enumerable, the defined method is not
  • the assigned method cannot use the super keyword
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Some restrictions apply when defined as method as part of the class definition:

  • It cannot be an arrow function
  • It cannot serve as a constructor

Those restrictions do not apply when using the .prototype.doSomething = notation.

Those restrictions do not hold either with the newer field declaration feature (experimental, in stage 3 at the time of writing):

One can assign an arrow function to such a field, or a function. In the latter case, that function can serve as a constructor.

However, a function assigned to an instance field is not a prototype method, but an instance member, and so it would not exactly correspond to what you would do with the .prototype alternative in your question.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    Actually you can do arrow functions ( `doSomething = () => ... `) – vittore Feb 24 '19 at 20:17
  • 1
    As mentioned, your first point is incorrect as per the [istance field](https://tc39.github.io/proposal-class-fields/) proposal. Although then it is an *instance method* rather than a method. So then with two instances `f1` and `f2` it does not hold that `f1.doSomething === f2.doSomething` like it would have with methods on the prototype. – Guy Waldman Feb 24 '19 at 20:29
  • Thank you both, I have added this information & qualified this point. – trincot Feb 24 '19 at 20:38
0

If you look at class code transpiled to ES < 6 you'll see it is similar but quite different.

In a nutshell class will do this (pseudocode):

Object.defineProperty(Foo.prototype, 'doSomething', doSomething)
José Salgado
  • 981
  • 10
  • 25
vittore
  • 17,449
  • 6
  • 44
  • 82