Reputation: 3969
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) { };
Upvotes: 0
Views: 55
Reputation: 1065
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?.
Upvotes: 1
Reputation: 943480
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.
Upvotes: 3