In a nutshell, I'm trying to define a variable in the window
which stays in sync with myValue
within the class. So window.myGlobalVarName
should always equal myValue
within the class.
I'm using Object.defineProperty
to try to prevent the variable from being re-assigned in the window
.
However, whenever get()
is called, this
is the window
object, not this
within the class. Am I missing something obvious here? There's plenty of examples of using get()
to return values within classes using this
- what am I doing differently?
class MyClass {
constructor() {
this.myValue = 1
this.globalVarName = "myGlobalVarName"
this.setGlobalObject()
}
setGlobalObject() {
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get() { return this.myValue } // "this" is actually "window"
})
}
}
}
I can resolve this returning the value of a function, but could I be doing this a better way?
setGlobalObject() {
const getMyValue = () => this.myValue // Return current value of this.myValue
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get() { return getMyValue() } // Returns the actual value from the class
})
}
}