How Object.getPrototypeOf(obj) works?
As per definition Object.getPrototypeOf(obj) should return prototype property of an Object or in another way it is same as obj.constructor.prototype.
Objects created with new use the value of the prototype property of their constructor function as their prototype.
Lets take an example:
>element = document.getElementById("test")
>a = Object.getPrototypeOf(element)
HTMLDivElement
Let’s say HTMLDivElement is the prototype of element.
>a.constructor.prototype
HTMLDivElement
so a.constructor.prototype is HTMLDivElement so Object.getPrototypeOf(a) should return HTMLDivElement but it returns HTMLElement. I am totally confused with definition of getPrototypeOf().
>b = Object.getPrototypeOf(a)
HTMLElement —-> why? a.constructor.prototype is HTMLDivElement
Actually it’s returning proto property of prototype, isn’t it wrong as per definition of getPrototypeOf()?
>a.constructor.prototype.__proto__
HTMLElement
quote from https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance_Revisited
NOTE that prototype is also AN OBJECT, so it ALSO CAN HAVE IT’S OWN UNIQUE PROTOTYPE
so code that make you confuse look like this
can be translated to this
I think it’s now clear that
a != b1) Every object in JavaScript has a prototype, you can access it through the
__proto__property2) Function is also an object in Javascript
3) Functions also have a
prototypeproperty4) We can create objects in JavaScript by calling function with keyword
new4) Function
prototypeis the initial__proto__for any objects created by themTo create new object we can write something like this
this code is equal to this
PS: also read this
https://stackoverflow.com/a/9220317/474290
and this
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance_Revisited