Take a look at the following code:
function Primate() {
this.prototype = Object;
this.prototype.hairy = true;
}
function Human() {
this.prototype = Primate;
}
new Human();
When you inspect new Human()
, there's no hairy
member. I would expect there to be one. Is there another way I'm suppose to inherit from Primate
? Something involving Object.create()
(ECMAScript5 is fine to use in my scenario)?
As your code is written, objects created using new Human()
will have a property called prototype
whose value is a reference to the Primate
function. That's clearly not what you want (and it's not particularly special).
A few things:
You usually want to modify the prototype
of a function that's intended to be used as a constructor (with the new
operator). In other words, you want to set the prototype
on Human
(not on an instance of Human
).
The value you assign to the prototype
should be an instance of the desired type (or, if no initialization work is necessary, the desired type's prototype
), not a reference to its constructor.
It's never necessary to explicitly assign Object
(or Object
instances) to a function's prototype
. This is implicit.
You probably want something more like this:
function Primate() {
this.hairy = true;
}
function Human() {}
Human.prototype = new Primate();
Human.prototype.constructor = Human;
var h = new Human();
The Human
referenced by h
has a property called hairy
whose value is true.
In the previous example, hairy
is assigned its value only once Primate
is invoked, which is why Human.prototype
must be assigned an instance of Primate
. This could instead be written so that no such initialization is necessary.
Example:
function Primate() {}
Primate.prototype.hairy = true;
function Human() {}
Human.prototype = Primate.prototype;
Human.prototype.constructor = Human;
var h = new Human();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With