In this particular case you can replace the lines for a simple reason:
function Dog(color, age) {
this.color = color;
Animal.call(this, age); // This line
}
Here, you're calling Animal's constructor with call
providing it this
thus establishing Animal's context manually. And so this
inside function Animal
will always refer to the Dog
's object. That's why a new
won't make a difference at all.
Strictly speaking, you're not actually doing proper prototypal inheritance. You can confirm that by doing:
dog_b.hasOwnProperty('age'); // => true
This is actually called constructor stealing
where Dog
stealing Animal
's constructor. The walk
method though is on Animal
's ctor.
Which means the age
property is on Dog
itself and not on Animal
. Why is that? Again, because you're establishing Animal
's constructor context manually to be that of the Dog
.
Edit:
In Javascript there are various ways of describing and attaining inheritance, and since this is not a place for writing a book I'll be quick.
What you're doing is called Parasitic Combination Inheritance
(you don't have to remember the term). It's not wrong, it's simply another way of obtaining inheritance (which is prototypal only for functions that are on Animal.prototype
). If it's working for you I'd say take it. If you really really want Animal
's age
to be on Animal
, then you'll face problems when using constructors to obtain inheritance.
One way of doing this would be:
function inherit(o){
function F(){}
F.prototype = o;
return new F();
}
var foo = {
name: 'some'
}
var bar = inherit(foo); // bar.name refers to the object on foo
As you can see, prototypal inheritance is usually used for object literals (think angular's scope object).