Why doesn't property writing concretize the prototype chain in Javascript?

I have been looking at this answer for a while, and I canโ€™t circle my head around it: https://stackoverflow.com/a/4128/

Summarizing:


Only the property reads the search for the prototype chain, and does not write. Therefore when you install

myObject.prop = '123'; 

He is not looking for a chain, but when you set

 myObject.myThing.prop = '123'; 

there is a subtle reading inside this write operation , which tries to find myThing before writing to its support. Therefore, why the entry in object.properties from the child object occurs at the parent objects.


I basically ask someone to clarify this thin reading operation. MyObject.myThing is evaluated first, returning a reference to the myThing object (which then has its own prop set of properties)? Is there any source where I can justify this (Mozilla, Javascript source code, etc.)?

+6
source share
1 answer

inside this write operation there is a subtle reading that myThing tries to find before writing on its support. Therefore, why the entry in object.properties from the child object occurs at the parent objects.

This is not a subtle reading. This is a regular reading.

 obj.prop1.prop2 = "foo" 

interpreted as (obj.prop1).prop2 = "foo" . Assuming the imaginary primitives read and write , it runs as

 write( read(obj, 'prop1'), 'prop2', "foo") 

if it becomes clearer. In other words, first prop1 read from obj . advising the prototype chain how normal it is to read. If it is not found in the instance, but in the prototype chain, then the result is prop1 on the prototype.

Next prop2 install prop2 on the object obtained as a result of obj.prop1 . If it is a prototype, it is prop1 , then the property prop2 set to prop1 on the prototype. If prop1 was found in the instance, then prop2 set to prop1 in the instance.

There is no change in the basic principle that reads, consult the prototype chain, and the records are always on the recordable object (without reference to the prototype chain).

Please note that in this case there may be subtle differences in the presence of setters and getters on the prototype.

In order not to confuse yourself and others, it is better to avoid storing data on the prototype. Think of the prototype as exclusively, or above all, as a way of sharing the methods of objects created from this prototype. The use of prototypes for data storage should ideally be limited to truly persistent data that is shared between instances.

+4
source

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


All Articles