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.