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 & functions from it.
function Bar(){}
function Baz(){}
Then instantiate my objects:
var bar = n开发者_StackOverflow中文版ew 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),
function Foo() {}
Foo.prototype.foo1 = null;
Foo.prototype.foo2 = function() { return false;};
then assigning the parent's prototype to the child's prototype is sufficient:
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 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:
function Bar() {
Foo.call(this);
}
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:
Bar.prototype = new Foo();
this should work (also in IE actually), but it has two major flaws:
All the instance properties set up in
Foo
will become properties shared by allBar
instances.What if
Foo
expects some arguments that are only available when you create aBar
instance?
have a look to Classy or, if you like Ruby and want a more complete solution to JS.Class. Those libraries helps you with object orientation in javascript ad hide prototype to the developer.
Hope this helps
精彩评论