为简单起见,这是伪代码。我想知道使用构造函数创建和重写值的最佳方法。
var RectConst = function (dim) {
var width = dim.x + dim.w, height = dim.y + dim.h;
this.shape = ctx.rect(dim.x, dim.y, width, height);
this.returnvalue = {width: width, height: height};
}
function drawRect(newshape) {
var Rect = new RectConst(newshape);
rectObj = Rect.returnvalue;
if(rectObj.width === 255){
//~ change the values in the shape function
}
ctx.save();
ctx.lineWidth = "1";
ctx.strokeStyle = "blue";
ctx.stroke();
ctx.restore();
}
drawRect({x: 200, y: 400, w: 200, h: 400});
答案 0 :(得分:1)
你可以这样做,
var RectConst = function (dim) {
var width = dim.x + dim.w, height = dim.y + dim.h;
this.shape = function(x,y,wid,hei) {
x = x || dim.x;
y = y || dim.y;
wid = wid || width;
hei = hei || height;
return ctx.rect(x, y, wid, hei);
}
this.returnvalue = {width: width, height: height};
}
现在您可以覆盖函数shape
,
if(rectObj.width === 255){
rectObj.shape(); // This will work with default values.
rectObj.shape(100,200,300,400); // This will work with overridden values.
}