【发布时间】:2018-07-04 12:00:51
【问题描述】:
我来自 Java 背景,并希望以类似的方式提及事物。 我不知道在哪里看。 伪代码:
var elements = [];
class Element
{
constructor()
{
this.isClicked;
}
mouseOver()
{
///returns true if mouse is over
}
click()
{
this.isClicked = true;
}
unclick()
{
this.isClicked = false;
}
}
class Parent extends Element
{
constructor()
{
this.children = [];
this.x = 0;
this.y = 0;
elements.push(this)
}
addChild()
{
children.push(new Child(this));
}
}
class Child extends Element
{
constructor(Parent p)
{
this.parent = p;
this.x = 0;
this.y = 0;
elements.push(this)
}
move()
{
this.x = parent.x;
this.y = parent.y;
}
}
var liveElement;
function mousePressed()
{
for(Element e : elements)
{
if(e.mouseOver)
{
liveElement = e;
liveElement.click();
}
}
}
function mouseReleased()
{
liveElement.unclick();
liveElement = null;
}
在原生 JavaScript 中可以做这种事情吗?我还想水平引用elements 中的所有对象。 Child 对象应该能够在需要时引用到 parent。
【问题讨论】:
-
查看打字稿:typescriptlang.org
-
删除类型注释,你得到的大部分是有效的 JS。
-
你的层次结构真的有问题。孩子本身不能成为父母,因此这不适合一棵树。
-
@Bergi 你是否建议我将它们一起包装到
Elements类中并取消Parent和Child? -
@jackoverflow 可能,虽然我不知道你想做什么。
标签: javascript object hierarchy