0

There are many questions regarding Javascript's implementation of inheritance, although I've not found an answer for why prototypes, in all examples and answers I've seen, are declared outside of the "class". Furthermore it seems using this.prototype can't be used, which seems unintuitive to those from an OOP background.

Is there any difference between:

function AClass() {
   AClass.prototype.AMethod = function(parms) { };
}

and

function AClass() { }
AClass.prototype.AMethod = function(parms) { };
Lee
  • 3,869
  • 12
  • 45
  • 65

2 Answers2

3

The difference is exactly the same as any other statement that you might put inside a function or outside a function. If it is inside the function, it runs when the function is called.

It doesn't make sense to redefine part of the "class" every single time an object is instantiated from it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • implicitly that mean that the methods on the prototype you want to declare are unknown until the first `AClass` is instantiated – Hacketo Sep 15 '15 at 16:34
  • Well if that's the case why do so many people place the declarations outside the main function? It's so prevalent that for a while I thought it was the only way of implementing "methods" – Lee Sep 15 '15 at 16:35
  • @Lee — Because, as I said, it doesn't make sense to redefine what a `AClass` means every single time you create an instance of it. – Quentin Sep 15 '15 at 16:36
  • Ah I see, it only just sunk in what you meant by that. Does this have any significant effect on overhead? I find it interesting JS engines don't optimise this in some way. – Lee Sep 15 '15 at 16:39
1

Every time you call AClass you are redefining AMethod if it's put inside the function scope. It slows down the code. Prototypes are useful when you will be creating many objects with duplicated functionality. Here is a similar question delving in related discussion in more detail Use of 'prototype' vs. 'this' in JavaScript?.

Community
  • 1
  • 1
Karolis Ramanauskas
  • 1,045
  • 1
  • 9
  • 14