Gordon
Gordon

Reputation: 47

How do I over write return values in javascript constructor functions?

This is pseudo code for simplicity. I want to know the best way to use the constructor functions to create and over write values.

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

Upvotes: 1

Views: 32

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do it in this way,

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

Now you can override the default values of function 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.
}

Upvotes: 1

Related Questions