简体   繁体   English

面向对象的Javascript

[英]Object-oriented Javascript

this is my first attempt at oo javascript: 这是我第一次尝试javascript:

function GuiObject() {
  this.x = 0;
  this.y = 0;
  this.width = 0;
  this.height = 0;
  this.parent = null;
  this.children = [];

  this.getWidth = function() 
  {
    return this.width;
  };
  this.getHeight = function() 
  {
    return this.height;
  };

  this.paint = function(ctx)
  {

  };

};



function paintGui(ctx, root)
{
  ctx.save();
  ctx.translate(root.x, root.y);
  root.paint(ctx);
  for (int i=0; i<root.children.length; ++i)
  {
    paintGui(ctx, root.children[i]);
  }
  ctx.restore();
};

Now in the paintGUI function, the line root.children.lengths throws an error: 现在在paintGUI函数中,行root.children.lengths引发错误:

Uncaught SyntaxError: Unexpected identifier. 未捕获到的SyntaxError:意外的标识符。

What did i do wrong? 我做错了什么?

Thanks! 谢谢!

It's hard to say what your actual problem is without looking at the code that actually constructs a GuiObject but for what it's worth, here's a better way to write that 'class'. 如果不看实际构造GuiObject的代码,很难说出您的实际问题是什么,但是对于它的价值而言,这是编写该“类”的一种更好的方法。

function GuiObject() {
  this.x = 0;
  this.y = 0;
  this.width = 0;
  this.height = 0;
  this.parent = null;
  this.children = [];
}

GuiObject.prototype.getWidth = function() 
{
    return this.width;
};

GuiObject.prototype.getHeight = function() 
{
    return this.height;
};

GuiObject.prototype.paint = function(ctx)
{

};

Doing it this way, every instance can share the same methods. 这样,每个实例可以共享相同的方法。 The other way, you would be creating new function objects for every instance you created. 另一种方法是,您将为创建的每个实例创建新的函数对象。 The only reason to ever define the methods in the constructor instead of attaching them to the prototypes is if they need to have access to private members that don't ever get attached to this . 有史以来定义不是将其附加到原型的构造方法的唯一原因是,如果他们需要访问该永远不得到重视私有成员this

int i ? int i What's that supposed to mean in Javascript then? 那么,在Javascript中这意味着什么呢? I think you meant var i . 我想你的意思是var i

BTW, In common with all the other people who responded, I looked at your code and didn't spot it immediately. 顺便说一句,与所有其他答复的人一样,我查看了您的代码,但没有立即发现它。 What I then did was copy/paste your function into the Javascript Console and gradually removed lines until it stopped complaining. 然后,我要做的就是将您的函数复制/粘贴到Javascript控制台中,并逐渐删除行,直到不再抱怨为止。 It's a useful technique to try out little bits of javascript. 试用一点点javascript是一项有用的技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM