繁体   English   中英

如何不通过争论仍然使功能工作?

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

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

然后我想调用这样的函数:

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

如您所见,我跳过了lWidth参数。 我希望函数仍然有效,即使lWidth没有作为参数传递。 我该怎么做? Atm,它可能会认为someCapStylelwidth

当你有大量的参数传递给你的函数时,使用一个对象:

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

在这种情况下,你不会依赖于参数的数量和它们的表示顺序。

所以你可以重写你的功能:

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

当你没有传递任何参数时,会传递undefined值,所以只需检查函数是否已经传递参数:

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

因此,为了不传递lWidth ,只需将undefined作为其值传递

PS最好的方法是使用单个参数args ,它将包含所有当前参数作为属性的对象。

你想要的是部分评估drawLine函数,为lWidth分配一个常量值。 有一个名为Jeene的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();
}

Function.prototype.specialize = net.higherorder.jeene.Jeene.make();

var drawLine2 = drawLine.specialize({
    lWidth: null // or whatever value you want
});

然后使用drawLine2 ,如下所示:

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

这称为特化,是一种非常有用的模式。 阅读更多相关信息: 无限邻居:Futamura医生的三个预测

您可以将可选参数放在参数列表的末尾。 这样,如果你把它留下,其他参数不会受到影响。

另一种选择是传递具有您想要定义的属性的单个对象,例如

function drawLine(options) {
    options.ctx.beginPath();
    options.ctx.moveTo(options.sX, options.sY);
    options.ctx.lineTo(options.eX, options.eY);
    // etc.
 }

你不能在Javascript中使用“函数重载”,但这是一种实现你想要的方法:

如何在javascript中重载函数?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM