I discovered to my complete surprise today that the following code errors:
class Base {
get foo() { return 42 }
}
class Derived extends Base {
constructor() {
super()
console.log(this, Object.getOwnPropertyDescriptor(this, 'foo'))
this.foo = 52
}
}
new Derived()
Here's the output:
Derived {} undefined
/Users/andy/clarity/src/server/temp.js:14
this.foo = 52;
^
TypeError: Cannot set property foo of #<Base> which has only a getter
at new Derived (/Users/andy/clarity/src/server/temp.js:11:5)
Where is this behavior specified and how does the VM enforce it?
I would have thought that assignment is only forbidden to an own read-only of an object, yet in this case the VM seems to be checking up the prototype chain.
To add to my confusion, the following assignment doesn't error but has no effect:
const base = {
get foo() {return 42}
}
const derived = Object.create(base)
derived.foo = 58
console.log(derived.foo) // outputs 42???
There's obviously a lot more going on under the hood in a property assignment than I thought. I guess people are right that I should read the spec