Clarification needed to create a prototype / object and circuit traversal

While I'm still trying to read β€œYou Don't Know JS,” I'm starting to have a good idea (I love this series). I think I have a prototype, but I came across below code.

var myObject = { a:2 }; Object.getOwnPropertyDescriptor(myObject, "a"); 

And although I fully understand the result and its meaning, I tried to use my understanding (or lack thereof) of the prototype and wanted to do it below.

  myObject.getOwnPropertyDescriptor 

I thought that it would move the proto chain to the prototype of the object and get this method, but as it turned out, the prototype of the object does not have this (suppose that this is not part of the prototype of the object, I look at the document, at least I do not consider it part prototype, and he says this is a method). Therefore, instead of being Object.prototype.getOwnPropertyDescriptor, I assume it is just Object.getOwnPropertyDescriptor.

I understand this correctly and why is the cause of the Object method not in all prototypes?

+5
source share
2 answers

it's not part of the Object prototype ... it's a method

You are absolutely right. This can be checked right away in the js console:

 > Object.getOwnPropertyDescriptor getOwnPropertyDescriptor() { [native code] } > Object.prototype.getOwnPropertyDescriptor undefined 

In a more strictly OOP language, you can call getOwnPropertyDescriptor static method. More correctly, this is not part of the prototype chain.

+2
source

In fact, Object.getOwnPropertyDescriptor(myObject, "a") calls myObject.GetOwnProperty("a") , but this is an internal method. a source

We can only speculate why this was done in this way, but I think it makes sense to define these utility functions as methods of the Object Object instead of making them inheritable via Object.prototype .

A more obvious example would be the Object.keys method. If it was Object.prototype.keys , it would cause problems every time we wanted to create var inMyPocket = { keys : true } . So now, to reliably enumerate the keys object, we will need to use Object.prototype.keys.call( inMyPocket ) , because we cannot be sure that inMyPocket.keys() referencing the prototype method or being overridden.

+1
source

Source: https://habr.com/ru/post/1238413/


All Articles