Reputation: 327
I'm implementing functions in javascript that inherit from a parent class. It works perfectly with this style of code.
function Foo(){}
Foo.prototype = {
constructor: Foo,
name: 'foo',
tostring: function()
{
return this.name;
}
};
function Bar(){}
Bar.prototype = new Foo();
Bar.prototype.name = 'bar';
var b = new Bar();
console.log(b.tostring()); // says 'bar'
This is okay. But I have a lot of properties in Bar and I don't want to repeat Bar.prototype.someProp every time so I used the shorthand version and it isn't inheriting.
function Bar(){}
Bar.prototype = new Foo();
Bar.prototype = {
constructor: Bar,
name: 'bar'
};
console.log(b.tostring()); // doesn't work since the method doesn't exist
I'm assuming Bar.prototype is being overwritten by the native Object of Javascript. How can I inherit using the shorthand Bar.prototype = {}
and avoid repetition?
Upvotes: 2
Views: 49
Reputation: 1
If you use…
Bar.prototype = {
constructor: Bar,
name: 'bar'
};
…you're overwriting everything in the Bar
prototype, replacing it with a new object. Try setting Bar.prototype.constructor = xxx
and Bar.prototype.name = 'bar'
individually.
You could define a helper function to reduce repetition but it's probably not worth it if you only need it once:
function extend_with(obj, kv) {
for (var k in kv) {
obj[k] = kv[k];
}
}
extend_with(Bar.prototype, {
constructor: Bar,
name: 'bar'
});
Upvotes: 2