Javascript and inheritance

Say I have a class:

function Foo() { this.foo1 = null; this.foo2 = function() { return false;}; } 

And I want other objects to inherit variables and functions from it.

 function Bar(){} function Baz(){} 

Then create instances of my objects:

 var bar = new Bar(); bar.foo1 // returns null bar.foo2() // returns false 

What is the correct function to enable Foo in Bar and Baz ?


I already did Bar.prototype = new Foo(); but it looks like it was failing in our beloved IE (<9).

+4
source share
2 answers

If you attach all the properties to the prototype (which is preferable, at least for the methods),

 function Foo() {} Foo.prototype.foo1 = null; Foo.prototype.foo2 = function() { return false;}; 

then assigning a parent prototype to a child prototype is enough:

 function inherit(Child, Parent) { var Tmp = function(){}; Tmp.prototype = Parent.prototype; Child.prototype = new Tmp(); Child.prototype.constructor = Child; } inherit(Bar, Foo); 

Here we used an intermediate design function to decouple the two prototypes. Otherwise, if you change it, you will change the other as well (since they refer to the same object). This method is actually quite popular and is used by several libraries.

If not, you should call the parent constructor function inside the constructor function of the children:

 function Bar() { Foo.call(this); } 

This is what you should always do to assign the properties set in the constructor function to the current object.


One more note to your path:

 Bar.prototype = new Foo(); 

this should work (also in IE actually), but has two main drawbacks:

  • All instance properties created in Foo will become the properties that all Bar instances share.

  • What if Foo expects some arguments that are only available when creating an instance of Bar ?

+5
source

take a look at Classy or if you like Ruby and want a more complete JS.Class solution. These libraries help you with object orientation in the javascript ad hide prototype developer.

Hope this helps

+1
source

All Articles