【发布时间】:2021-11-18 15:50:00
【问题描述】:
我在 ES6 中有一个这样的基类:
class BasePlot {
props = {
'data': []
}
constructor() {
// do things but don't setup data
}
draw(data){
if (data && data.length )
this.props.data = data;
// Q: how to exit here if height and width are not yet available?
this.setScale()
this.setAxis()
}
setDimensions(height, width) {
this.props.height = height;
this.props.width = width;
}
}
该类永远不会被直接实例化,而只会用于继承。
除了构造函数之外,所有其他方法都可能以不可预知的顺序调用,这就是为什么在 draw 方法中,如果尚未为实例定义 height 和 width,我不想继续。
我可以简单地添加一个if 条件并退出,但这不是我的想法。
在子类中,我这样称呼父类draw:
class RectPlot extends BasePlot{
draw(data){
super.draw(data);
// DON'T EXECUTE if height and width are not set
// rest of the code
}
}
在这种情况下,当我调用子 draw 时,我首先调用父方法,如果尚未设置 height 和 width,我想从父方法退出(返回)但是也来自孩子。
我的意思是,是这样的:
// Parent
draw(data){
if (data && data.length )
this.props.data = data;
if(this.props.height && this.props.width)
this.setScale()
this.setAxis()
return true
}
else return false
}
}
// Child
draw(data){
if(super.draw(data)){
// proceed w rest of the code
}
else return false
}
这正是我想做的,除了我不想检查所有子类中的 if 是否父 draw 成功完成。
问:除了前面提到的在所有子类中重复 if-else 块之外,还有其他方法可以“提前退出”父和子方法吗?
【问题讨论】:
-
这都是可视化的,但也许如果你不使用
if (blah) {..} else return false;,你会使用if (!blah) return false;,这将是一个更清晰的代码......
标签: javascript inheritance ecmascript-6 es6-class