Say I have a Class:
function Foo() {
this.foo1 = null;
this.foo2 = function() { return false;};
}
And I want other objects to inherit variables & functions from it.
function Bar(){}
function Baz(){}
Then instantiate my objects:
var bar = new Bar();
bar.foo1 // returns null
bar.foo2() // returns false
What’s the proper function to include Foo in Bar and Baz?
I already did Bar.prototype = new Foo(); but it seems to fail on our beloved IE (<9).
If you attach all the properties to the prototype (which is preferable, at least for methods),
then assigning the parent’s prototype to the child’s prototype is sufficient:
Here we used an intermediate constructor function to “decouple” the two prototypes. Otherwise if you’d change one, you’d change the other one too (as they reference the same object). This way is actually pretty popular and used by a couple of libraries.
If not, you have to call the parent’s constructor function inside the child’s constructor function:
This is something you always should do, to assign the properties set up in the constructor function to the current object.
An additional remark to your way:
this should work (also in IE actually), but it has two major flaws:
All the instance properties set up in
Foowill become properties shared by allBarinstances.What if
Fooexpects some arguments that are only available when you create aBarinstance?