我有我的js的構造函數:如何將一個方法添加到JavaScript對象?
Function myobj(){
This.type = "triangle";
}
如何添加一個方法,它喜歡:
Triangle.mymethod();
我有我的js的構造函數:如何將一個方法添加到JavaScript對象?
Function myobj(){
This.type = "triangle";
}
如何添加一個方法,它喜歡:
Triangle.mymethod();
可以使用的原型:
// 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);
};
我正在創建一些形狀對象在畫布上繪製......現在我也明白爲什麼一個canvasobject會有用。 – 2013-05-04 09:53:40
您需要擴展的對象原型。
Triangle.prototype.myMethod = function(){
//method here;
console.log(this.type); //you can reference the instance via this
};
閱讀有關的原型,這是基本的東西可以在網絡上隨處可見。 – elclanrs 2013-05-04 09:45:44
這取決於你如何創建'三角形'。 – 2013-05-04 09:55:16