Question

I am trying to get my head around prototypal inheritance by using the Chrome Developer Console. This is the code I use to set up the Prototype Chain:

var Organism = Object.create(null);
undefined
var Animal = Object.create(Organism);
undefined
var Mammal = Object.create(Animal);
undefined
var Dog = Object.create(Mammal);
undefined
var Spot = Object.create(Dog);
undefined

I can add some properties to the Organism and the Mammal Objects:

Mammal.hasHair = true;
true
Organism.hasHair = false;
false

Next I define some variables for the Dog object:

Dog.numLegs = 4;
4
Dog.speak = function(){return 'woof, woof!';};
function (){return 'woof, woof!';}

Finally I define some variables for Spot

Spot.color = 'White';
"White"
Spot.pattern = 'Spots';
"Spots"
Spot.patternColor = 'Black';
"Black"
Spot.weight = 22
22

However for some reason when I inspect the Dog Object It outputs the properties like this and I cannot see it's prototype...

Spot;
Object {color: "White", pattern: "Spots", patternColor: "Black", weight: 22}

Or If I try this I still cannot see it's prototype...

dir(Spot);
Object
color: "White"
pattern: "Spots"
patternColor: "Black"
weight: 22

If I am not mistaken, should I not have a property called _proto_ which will point to the prototype of the Dog Object which is Mammal? How can I inspect the Object to see this Property?

Was it helpful?

Solution

You need to create the first object by using the prototype of the Object constructor like so:

var Organism = Object.create(Object.prototype);

Creating an object with null as the prototype will create an object with no properties at all including _proto_

for a more in depth look into Object.create check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

OTHER TIPS

Using var Organism = new Object(null); etc does create a prototype object, and works as expected.

Don't entirely have my head around this, but it appears this is due to a prototype not being created without a constructor. So, in constructing new Object() you create a prototype. However, Object.create() only returns an object, and if you try new Object.create() it's clear this is not a constructor.

Worth reading into constructors and prototypes: http://tobyho.com/2010/11/22/javascript-constructors-and/

I'd welcome a more thorough answer, since I would also have expected a prototype in the returned object. Having followed your steps, I replicated the same result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top