I'm not very well aquainted with javascript inheritance, and I'm trying to make one object inherit from another, and define its own methods:
function Foo() {}
Foo.prototype = {
getColor: function () {return this.color;},
};
function FooB() {}
FooB.prototype = new Foo();
FooB.prototype = {
/* other methods here */
};
var x = new FooB().getColor();
However, the second one overwrites the first one(FooB.prototype = new Foo() is cancelled out
). Is there any way to fix this problem, or am I going in the wrong direction?
Thanks in advance, sorry for any bad terminology.
Each object can only have one prototype, so if you want to add to the prototype after inheriting (copying) it, you have to expand it instead of assigning a new prototype. Example:
One solution would be:
Update: Regarding expanding with an existing object. You can always copy the existing properties of one object to another one:
As long as
proto
is a "plain" object (i.e. that does not inherit from another object) it is fine. Otherwise you might want to addif(proto.hasOwnProperty(prop))
to only add non-inherited properties.You can use an
extend
function which copies the new members to the prototype object.extend