Please, look at the following way to simulate inheritance in JavaScript. It's very simple and it does not use prototypes at all. It seems to work well, but I suspect something is wrong with it, just because people usually don't do like this. Can anybody explain me, what are disadvantages of this approach and what I am missing? Thanks a lot.
// The base class constructor
function Animal(name)
{
var _name = name; // local variable, not visible to subclass
this.greeting = function()
{
return "Hello, "+_name;
}
this.makeSound = function()
{
return "Don't know what to say";
}
}
// The subclass constructor
function Cow(name)
{
Animal.call(this, name); // call the base constructor
this.makeSound = function() // override base class's method
{
return "Mooooo!";
}
}
var myCow = new Cow("Burenka");
console.log(myCow.greeting()); // call inherited method
console.log(myCow.makeSound()); // call overriden method
UPDATE Thanks to everybody for answers and comments. Just to summarize:
This approach can be used, but there are some limitations:
- Every instance construction is performed from scratch rather than just setting a link to prototype — this may affect performance.
- Every instance contains definitions of all the base class's methods — wasting memory.
instanceof
won't work properly (i.e. won't treat the subclass instance as a base class instance).- If you override a method this way, you can not call the implementation from the base class when you need it (if you want just extend the functionality, not replace it completely).
- If you want to change the implementation of base class's methods dynamically, you need prototypes.
And of course there are other questions here for the same subject. See also: