简体   繁体   中英

Object-oriented Javascript

this is my first attempt at oo 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:

Uncaught SyntaxError: Unexpected identifier.

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'.

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 .

int i ? What's that supposed to mean in Javascript then? I think you meant 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. It's a useful technique to try out little bits of javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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