在JavaScript中引用对象的层次结构

时间:2018-07-04 12:00:51

标签: javascript object hierarchy

我来自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

1 个答案:

答案 0 :(得分:1)

是的,自ES2015(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)起,可以在JS中做类似的事情。如果该应用程序应在不同的浏览器和版本中运行,则建议您使用Babel(https://babeljs.io/)这样的编译器,因为最后的ES功能与旧版浏览器不兼容。子类和父类之间的关系可以在mdn参考(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super)中找到。希望对您有所帮助。

相关问题