开发者

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(o开发者_Go百科bj.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜