Harish
Harish

Reputation: 636

Why does the getPrototypeOf() return incorrect constructor in JavaScript?

var protoRabbit = {size: "small"};
var fastRabbit = Object.create(protoRabbit);
console.log(Object.getPrototypeOf(fastRabbit));

The above snippet prints:

Object { size: "small" }

Shouldn't this print protoRabbit {size: "small"} instead? What am i missing in my understanding?

Upvotes: 5

Views: 96

Answers (2)

basilikum
basilikum

Reputation: 10528

The name that is printed in front of the object is the name of the constructor function. Your object protoRabbit has the constructor Object, because you create this object, using an object literal:

var protoRabbit = {size: "small"};

If you want this object to have a different constructor, you have to use your own constructor function:

function Constr() {
    this.size = "small";
}
var protoRabbit = new Constr();
var fastRabbit = Object.create(protoRabbit);
console.log(Object.getPrototypeOf(fastRabbit)); //Constr { size: "small" }

EDIT

I have to agree with Demurgos' answer, that the result of console.log(obj); depends on the browsers implementation. So it can be different from browser to browser and can (apparently) sometimes even vary within one browser (link).

Upvotes: 6

Demurgos
Demurgos

Reputation: 1682

The name displayed in the console is not standard. It is up to each browser to provide the best context in their console when printing an object. The fact is that the objects contains the right properties, and that's all we really need.

Upvotes: 1

Related Questions