braam
braam

Reputation: 43

Why does a javascript object property assignment via the dot notation NOT trigger a setter defined for that property?

Any Javascript ninjas or people who have read ECMA-262 5th care 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 a bit confusing because I expected the two assignment notations to be functionally equivalent.

Upvotes: 4

Views: 1588

Answers (1)

Tim Down
Tim Down

Reputation: 324597

The fundamental difference is that obj.prop = foo is changing what the prop property of obj references, while obj.prop.bar = "Bar" is merely changing some property of the object to which obj.prop refers but not changing the reference itself.

Upvotes: 5

Related Questions