Search code examples
javascriptecmascript-5prototype-programming

Object.getPrototypeOf(o) method issue


I struggle to understand Object.getPrototypeOf(o). I'm playing with that method in below code.

var obj0 = {x: 10};

var obj1 = Object.create(null, {
  'name': {value: 'first object name', enumerable: false}, 
});

var obj2 = Object.create(obj1, {
  'location': {value: 'second object location'},
});

alert(Object.getPrototypeOf(obj0)); // [object Object]
alert(Object.getPrototypeOf(obj1)); // null
alert(Object.getPrototypeOf(obj2)); // TypeError: Cannot convert object to primitive value

I would appreciate any hint on:

1/ Why object2 returns TypeError?

2/ Is Object.getPrototypeOf method always returns [object Object] as the "highest object" in prototype chain? I would assume that it will give me it's "nearest" object in chain so ex. if there would be obj3 that has obj0 as prototype it would give me [obj0 Object] instead of [object Object].


Solution

  • This is simply a problem with using alert, which converts the alerted object to a String. [object Object] is the string representation of {}:

    ({foo: 'bar'}).toString(); // [object Object]
    

    You should use the console for your testing, which will show you a better representation of the object (see example on JSFiddle).

    Also in the example is a new object, obj3, which shows that Object.getPrototypeOf() does return the nearest object, not the root prototype.