JavaScript 在对私有变量使用 WeakMap 时扩展 class
JavaScript extend a class while using WeakMap for private variables
我通过使用 WeakMap()
编写了一些具有私有变量的 classes。我通过在 class 文件的顶部放置一个 WeakMap
来做到这一点。
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);
}
}
这很好用,我能够添加一些 getter 和 setter,它们具有验证和 type-checking。
现在我想将 class 扩展到另一个 class,但我在 child 和 [=] 之间共享私有 属性 信息时遇到问题48=] class 个文件。
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);
}
}
当从 startFlashing
中的 setInterval
函数调用 this.lightSwitch
时,它无法访问 object.
的状态
Uncaught TypeError: Cannot read property 'state' of undefined
at lightSwitch
这是因为这些功能分布在两个文件中吗?无论如何,我可以同时使用私有变量和 class 扩展吗?
你的一个问题是使用 setInterval where you pass a function. When that function is called, this
is not what you expected. You can use bind 强制它成为你想要的,比如 setInterval(this.lightSwitch.bind(this),5000)
我通过使用 WeakMap()
编写了一些具有私有变量的 classes。我通过在 class 文件的顶部放置一个 WeakMap
来做到这一点。
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);
}
}
这很好用,我能够添加一些 getter 和 setter,它们具有验证和 type-checking。
现在我想将 class 扩展到另一个 class,但我在 child 和 [=] 之间共享私有 属性 信息时遇到问题48=] class 个文件。
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);
}
}
当从 startFlashing
中的 setInterval
函数调用 this.lightSwitch
时,它无法访问 object.
Uncaught TypeError: Cannot read property 'state' of undefined
at lightSwitch
这是因为这些功能分布在两个文件中吗?无论如何,我可以同时使用私有变量和 class 扩展吗?
你的一个问题是使用 setInterval where you pass a function. When that function is called, this
is not what you expected. You can use bind 强制它成为你想要的,比如 setInterval(this.lightSwitch.bind(this),5000)