1

我有我的 js 构造函数:

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

如何向它添加方法,例如:

Triangle.mymethod();
4

2 回答 2

1

您可以使用原型:

// 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);
    };
于 2013-05-04T09:47:42.020 回答
0

您需要扩展对象原型。

Triangle.prototype.myMethod = function(){
  //method here;
  console.log(this.type); //you can reference the instance via this
};
于 2013-05-04T09:46:40.897 回答