简体   繁体   中英

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.

根本区别在于obj.prop = foo正在改变obj引用的prop属性,而obj.prop.bar = "Bar"只是改变了obj.prop引用的对象的某些属性,但没有改变引用本身。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM