Why does the obj property not change through the prototype?

var obj = { val:"num" } var obj2 = { value:2 } obj2.__proto__ = obj; console.log( obj2.val );//Берем значение из прототипа = num obj2.val = 3; //Меняем значение свойства val обьекта obj на 3 console.log( obj.val ); // => num. Ожидаю 3 console.log( obj2.val );// =>3 delete obj2.val; console.log( obj2.val ); // => num. ожидаю undefined console.log( obj.val ); // => num. ожидаю undefined 

    1 answer 1

    In this case, three operations are used:

    1. getting object property
    2. setting an object property
    3. object property deletion

    Getting the property

    1. If the object has the requested property, its value will be returned.
    2. If the object does not have the requested property, the request will be redirected to the prototype object. This will continue until the prototype becomes null .

    Setting a property

    1. If the object has a property to which you want to set a value, then the value of this property will be updated.
    2. If the object has no property that needs to be assigned a value, then the property will be added to the object with the specified value.

    Property removal

    1. If the object has a property that needs to be deleted, the property will be deleted and true will be returned.
    2. If the object has no property, false will be returned.

    In this regard, the code from the question can be commented like this:

     var obj = { val:"num" } var obj2 = { value:2 } obj2.__proto__ = obj; console.log( obj2.val );// в obj2 Нет свойства `val`, смотрим в прототип (obj) -> берем значение из прототипа obj2.val = 3; // в obj2 Нет свойства `val`, создаем свойство `val` и присваиваем ему значение `3` console.log( obj.val ); // => у объекта присутствует запрашиваемое свойство его значение возвращается -> num console.log( obj2.val );// => у объекта присутствует запрашиваемое свойство его значение возвращается ->3 delete obj2.val; // удаляем из `obj2` свойство `val` console.log( obj2.val ); // => в obj2 Нет свойства `val`, смотрим в прототип (obj) -> берем значение из прототипа console.log( obj.val ); // => num. Объект `obj` не менялся ни в одной строчке, следовательно значение то же, что и в начале. 
    • Visited @Grundy - skip, there is already an excellent answer, we are looking for unanswered questions further :) - user207618