In the following code, both uses of console.log(o.x)
print 1
. What happens to the assignment o.x = 2
? Is it just ignored?
var o = {
get x() {
return 1;
}
}
console.log(o.x); // 1
o.x = 2
console.log(o.x); // 1
In sloppy mode, yes, it'll just be ignored - the value "assigned" will be discarded. But in strict mode (which is recommended), the following error will be thrown:
Uncaught TypeError: Cannot set property x of
#<Object>
which has only a getter
'use strict';
var o = {
get x() {
return 1;
}
}
console.log(o.x); // 1
o.x = 2