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
JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.
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
a = Object.getPrototypeOf(element)
b = Object.getPrototypeOf(a)
can be translated to this
a = element.__proto__
b = element.__ptoto__.__proto__
I think it's now clear that a != b
1) Every object in JavaScript has a prototype, you can access it through the __proto__
property
2) Function is also an object in Javascript
3) Functions also have a prototype
property
4) We can create objects in JavaScript by calling function with keyword new
4) Function prototype
is the initial __proto__
for any objects created by them
To create new object we can write something like this
//here we define a function
function SomeFunctionThatCreateObject() {
this.someStringProperty = "blablabla";
}
var obj = new SomeFunctionThatCreateObject(); //we create new object with function
var p = Object.getPrototypeOf(obj);
this code is equal to this
var SomeFunctionThatCreateObject = function(@this) {
@this.someStringProperty = "blablabla";
return @this;
};
SomeFunctionThatCreateObject.prototype = {}; //note that prototype is also an object
var obj = {};
obj = SomeFunctionThatCreateObject(obj);
obj.constructor = SomeFunctionThatCreateObject;
obj.__proto__ = SomeFunctionThatCreateObject.prototype;
var p = obj.__proto__;
PS: also read this https://stackoverflow.com/a/9220317/474290 and this https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance_Revisited
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With