I am confused by the way property getters interact with constructor closure.
Below is a minimal example:
function Ctor() {
let closureX = 0
Object.assign(this, {
get publicX() { return closureX }
})
closureX++
console.log(closureX)
}
let o = new Ctor()
console.log(o.publicX)
Why is o.publicX
not changing when closureX
does ?
3
Answers
It is simply because that’s what
Object.assign
does – it does not assigngetters
orsetters
, it assigns the values associated with the keys to the other object. MDN Docs already clarifies that getters will be invoked on the source and setters will be invoked on the target:That last sentence is exactly what you are trying to do and it will not work.
You can verify this be checking its property descriptor and seeing that the new object did not inherit the
getter
from the source object, only thevalue
that getter returns:If you do want to accomplish this, the solution would probably be the old-fashioned
Object.defineProperty
to assign the getter:You already learnt the why. Now, a way to ‘solve’ this is to create a factory function. Additional advantage may be that with a factory you don’t need the
new
keyword anymore. For example:I actually stopped using constructors a couple of years ago and use factories for all kinds of code in a class free object oriented fashion. For example in this flagged enum factory.
let me break the constructor defination function for you.
The Object.assign() is a static method that copies all enumerable own properties from one or more source objects to a target object.
and get syntax binds an object property to a function that will be called when that property is looked up.
this is whole brief in short.
so when you copied the variable , its a deep copy means changes which are implemented further is not higlighted in the copied one.
i hope this will help.