JavaScript objects have the 'prototype' member to facilitate inheritance. But it seems, we can live perfectly well, even without it, and I wondered, what are the benefits of using it. I wondered what are the pros and cons.
For example, consider the following (here jsfiddle):
function Base (name) {
this.name = name;
this.modules = [];
return this;
}
Base.prototype =
{
initModule: function() {
// init on all the modules.
for (var i = 0; i < this.modules.length; i++)
this.modules[i].initModule();
console.log("base initModule");
}
};
function Derived(name) {
Base.call(this,name); // call base constructor with Derived context
}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.initModule = function () {
console.log("d init module");
// calling base class functionality
Base.prototype.initModule.call(this);
}
var derived = new Derived("dname");
console.log(derived.name);
derived.initModule();
A question is, why use 'prototype' at all? We can also do something like Derived = Object.create(Base);
for example (jsfiddle):
Base =
{
initModule: function() {
// init on all the modules.
for (var i = 0; i < this.modules.length; i++)
this.modules[i].initModule();
console.log("base initModule",this.name);
},
init: function(name) {
this.name = name;
this.modules = [];
}
};
Derived = Object.create(Base);
Derived.initModule = function () {
console.log("d init module");
// calling base class functionality
Base.initModule.call(this);
}
Derived.init("dname");
console.log(Derived.name);
Derived.initModule();