Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 434
Harish Avatar asked May 04 '15 15:05

Harish


2 Answers

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

like image 132
basilikum Avatar answered Nov 15 '22 21:11

basilikum


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.

like image 41
Demurgos Avatar answered Nov 15 '22 22:11

Demurgos