Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not pass arguements and still make the function work?

Tags:

javascript

function drawLine(ctx, sX, sY, eX, eY, sRGB, fRGB, lWidth, capStyle)
{
    ctx.beginPath();
    ctx.moveTo(sX, sY);
    ctx.lineTo(eX, eY);
    ctx.lineWidth = lWidth||5;
    ctx.strokeStyle = 'rgb(49, 129, 48)';
    ctx.lineCap = 'round';
    ctx.stroke();
    ctx.closePath();
}

And then I want to call the function like this:

drawLine(ctx, 50, 50, 100, 100, someStrokeStyle, someFillStyle, someCapStyle);

As you can see I have skipped the lWidth parameter. I want the function to still work, even when the lWidth is not passed as a parameter. How will I do this? Atm, it might think that the someCapStyle is the lwidth.

like image 973
Joe Slater Avatar asked Jan 14 '23 22:01

Joe Slater


2 Answers

When you have a big amount of arguments to pass into a function like you have, use an object:

function foo({param1: val1, parma2: val2}) {}

In that case you wont be depend on number of arguments and order of them being represented.

So you can rewrite your function:

 function drawLine(drawObj)
{
    ctx.beginPath();
    ctx.moveTo(drawObj.sX, drawObj.sY);
    ctx.lineTo(drawObj.eX, drawObj.eY);
    ctx.lineWidth = drawObj.lWidth||5;
    ctx.strokeStyle = drawObj.sRGB;
    ctx.lineCap = drawObj.capStyle;
    ctx.stroke();
    ctx.closePath();
}
like image 140
happyCoda Avatar answered Jan 19 '23 10:01

happyCoda


When you don't pass any argument, undefined value is passed instead, so just check in the function whether the argument has been passed or not:

if(typeof argument == "undefined") 
{ 
   argument = "default value";
}

So to not pass lWidth, just pass undefined as its value

P.S. the best way is to use a single argument args, which will be object containing all current parameters as properties.

like image 22
artahian Avatar answered Jan 19 '23 12:01

artahian