【问题标题】:Referring to a Hierarchy of Objects in Javascript在 Javascript 中引用对象的层次结构
【发布时间】: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 类中并取消ParentChild
  • @jackoverflow 可能,虽然我不知道你想做什么。

标签: javascript object hierarchy


【解决方案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) 中找到。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2012-09-27
    相关资源
    最近更新 更多