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(){
...
}
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(){
...
}
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:
.name
function
has a .prototype
and is constructible, the defined method doesn'tsuper
keywordSome restrictions apply when defined as method as part of the class
definition:
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.
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)