I wrote some classes that have private variables through the use of WeakMap()
. I did this by placing a WeakMap
at the top of the class file.
light.js
let privateVars = new WeakMap();
class Light {
constructor(state, brightness) {
let info = {"state": state, "brightness": brightness, "createdAt": Date.now()};
// Save info into privateVars
privateVars.set(this, info);
}
switch() {
let info = privateVars.get(this);
info.state = !info.state;
privateVars.set(this, info);
}
}
This worked fine, I was able to add some getters and setters, which had validation and type-checking.
Now I'm wanting to extend that class to another class but I'm having trouble sharing the private property information between the child and parent class files.
flashingLight.js
let privateVars = new WeakMap();
let flashing;
import Light from './light.js';
class FlashingLight extends Light {
constructor(state=false, brightness=100, flashMode=true) {
super(state, brightness);
let info = {"state": state, "brightness": brightness, flashMode: flashMode, "createdAt": Date.now()};
privateVars.set(this, info);
if(flashMode===true) {
this.startFlashing();
}
}
startFlashing() {
flashing = setInterval(this.lightSwitch,5000);
}
}
When this.lightSwitch
is called from the setInterval
function inside startFlashing
it can't access the state of the object.
Uncaught TypeError: Cannot read property 'state' of undefined
at lightSwitch
Is this because these functions are spread out across the two files? Is there anyway around this so that I can use both private variables and class extensions?
One of your problems is the usage of setInterval where you pass a function. When that function is called, this
is not what you expected. You can use bind to force it to be what you want, like setInterval(this.lightSwitch.bind(this),5000)