Let a prototype function have helper functions with an inherited environment

The presence of a prototype with various functions, mainly with canvas. Usually:

function CanvasPain() {
    ...
}

CanvasPaint.prototype.drawFoo = function(x, y) {
    this.ctx.moveTo(x, y);
    ...
};

I have some functions, such as paintGrid (), where I would like to have helper functions, but also being property-based objects. (I donโ€™t know how to say this.) Example:

CanvasPaint.prototype.grid = function() {
    this.paint = function() {
        this.ctx.moveTo(0, 0);
         // Here this.rows should be a property of CanvasPaint.prototype.grid()
         // and not CanvasPaint()
        for (var i = 0; i < this.rows; ++i) {
            ... paint lines
        }
    };
};

And then when you can say, for example:

var CP = new CP();

// And in some function:
   this.grid.rows = 10;
   this.grid.cols = 10;
   this.grid.paint();

The reason for this is to make the code cleaner. At the moment, I'm using something like this:

function CanvasPain(arg) {
    ...
    this.properties = {};
    this.properties.fig1 = {a:123, b:111};
    this.properties.grid = {
                rows = arg.rows;
                cols = arg.cols;
                live = 1;
    };
}

CanvasPaint.prototype.paintGrid = function() {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.ctx.moveTo(0, 0);
    for (var i = 0; i < this.properties.grid.rows; ++i)
        ...
}

CanvasPaint.prototype.foo = function() {
    this.paintGrid();
}

This is also not very good. I want to get rid of the "properties" object and instead set these properties to the corresponding function, if any. Like rows and columns for a grid, refers to a grid of function objects.

, , ?

CP.grid = new CP.grid();, this.cxt .. CP.grid.paint(), , , paint.

+3
1

paint() CanvasPain, , rows cols.

, CanvasPain .grid:

function CanvasPain(arg)
{
  // ...

  // generate grid object
  this.grid = function(p) {
      // return public interface
      return {
          paint: function() {
              p.ctx.moveTo(0, 0);
              for (var i = 0; i < this.rows; ++i) {
                  //... paint lines
              }
          }
      };
  }(this);
}

p CanvasPain.

var CP = new CanvasPain();

CP.grid.rows = 10;
CP.grid.cols = 10;
CP.grid.paint();
+2

All Articles