I’ve just read The Good Parts, and I’m slightly confused about something. Crockford’s example of pseudoclassical inheritance goes like this:
var Mammal = function (name) {
this.name = name;
};
Mammal.prototype.get_name = function () {
return this.name;
};
Part of the problem with this is that the constructor has “its guts hanging out” – the methods are outside of the constructor function. I don’t see what’s wrong with assigning get_name to this inside the constructor though. Is it because we’d end up with multiple copies of the get_name method?
Yes, that’s basically it.
By assigning them to the prototype, they will be inherited by all instances of
Mammal: there will only be one single copy of those functions in the entire system, no matter how manyMammals there are.