Why use 'prototype' for javascript inheritance?

inheritance, javascript

Solution

If you don't use the prototype, the methods are redefined with every class. That is to say, `new Base; new Base; new Base` will create six functions in the second example. This takes more time and space. `Derived` will also create its own functions.

Additionally, you can't use the prototype to change methods for each instance on the fly (or add new methods), which could be potentially helpful -- especially across modules.

However that's not to say that you should always use the prototype for every method. Each situation is different.

`prototype` also allows you to call methods in a different context without creating an instance (as in the case of `Array.prototype.forEach.call` on an array-like object).

Problem

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(); ```

Original source