Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inheritance: When where's my derived members?

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)?

like image 894
user979672 Avatar asked Jan 30 '12 18:01

user979672


1 Answers

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();
like image 172
Wayne Avatar answered Oct 14 '22 05:10

Wayne