如何将方法添加到javascript对象?

时间:2013-05-04 09:45:02

标签: javascript

我有我的js构造函数:

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

如何添加方法,如:

Triangle.mymethod();

2 个答案:

答案 0 :(得分: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);
    };

答案 1 :(得分:0)

您需要扩展对象原型。

Triangle.prototype.myMethod = function(){
  //method here;
  console.log(this.type); //you can reference the instance via this
};