Why does assigning a property to a javascript object through dot notation NOT trigger the setter defined for this property?

Any Javascript ninjas or people who read ECMA-262 5th leaving to explain the following behavior?

var obj = { p: {}, set prop(val){ for (var key in val){ this.p[key] = "Set: " + val[key]; } }, get prop(){ return this.p; } } obj.prop = { // Assignment triggers setter foo: "Foo" } obj.prop.bar = "Bar"; // Assignment does not trigger setter console.log(obj.prop.foo); // Set: Foo console.log(obj.prop.bar); // Bar 

I found the above behavior is a bit confusing because I expected the two assigned designations to be functionally equivalent.

+4
source share
1 answer

The fundamental difference is that obj.prop = foo changes the prop properties of the obj links, and obj.prop.bar = "Bar" just changes some property of the object that obj.prop belongs obj.prop , but does not change the link itself.

+5
source

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


All Articles