I wonder what is the difference between these two approaches. They both work but I don’t understand if the 2nd approach might have undesirable implications?
// A. Putting a prototype method outside the function declaration (what I would normally do)
var Cat = function(){
}
Cat.prototype.eat = function(){
// implementation
}
// B. Putting a prototype method inside the function declaration (it works too but the scoping seems different)
var Cat = function(){
Cat.prototype.eat = function(){
// implementation
}
}
Every object has a prototype. Prototypical inheritance allows you to assign either an entirely new prototype (similar to the classical inheritance):
Or directly add variables and methods to the current class’s prototype:
Your second example simply reassigns the
eatfunction to the Cat prototype every time theCatclass is initiated, which is useless but doesn’t take up any memory because it just overwrites the old value.Why is this useful? Remember that functions are objects. For every instance of your class, each variable and function defined in that class takes up it’s own memory. Using prototypical inheritance, you can share common methods, thus not taking up the extra memory for each instance.
Why is this not as useful? You don’t have access to private variables.
Keep in mind that this is not the same thing as a static method, which can be declared as: