如何在javascript构造函数中重写返回值?

时间:2016-03-13 05:02:32

标签: javascript

为简单起见,这是伪代码。我想知道使用构造函数创建和重写值的最佳方法。

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});

1 个答案:

答案 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.
}