1

I have my js constructor:

Function myobj(){
    This.type = "triangle";
}

How do I add a method to it like:

Triangle.mymethod();

2 Answers2

1

You can use prototypes:

// The standard canvas object
    function CanvasObj(canvas, x, y, w, h, fill){
        this.x = x||0;
        this.y = y||0;
        this.w = w||0;
        this.h = h||0;
        this.objects = [];
        this.ctx =  context_for(canvas);
        this.init(canvas, fill);
    };

// Initial set-up of the canvas
    CanvasObj.prototype.init = function(canvas, fill){
        position_element(canvas, this.x, this.y);
        resize_canvas(canvas, this.w, this.h);
        draw_rect(this.ctx, 0, 0, this.w, this.h, fill);
    };
Vlad Otrocol
  • 2,594
  • 6
  • 30
  • 54
  • 1
    I was creating some shape objects to draw on my canvas ... Now i also understand why a canvasobject would be useful. – Rohina Jogi May 04 '13 at 09:53
0

You need to extend the objects prototype.

Triangle.prototype.myMethod = function(){
  //method here;
  console.log(this.type); //you can reference the instance via this
};
Kevin Bowersox
  • 90,944
  • 18
  • 150
  • 184