Javascript 组合函数以降低复杂性
使这三项职能更有效的最佳方式是什么?他们有共同的逻辑Javascript 组合函数以降低复杂性,javascript,Javascript,使这三项职能更有效的最佳方式是什么?他们有共同的逻辑 function setBoxWidth(type) { var boxWidth; if (type) { boxWidth = 308; } else { boxWidth = 400; } return boxWidth; } function setAspectWidth(type) { var bw; if (type) { bw = 192
function setBoxWidth(type) {
var boxWidth;
if (type) {
boxWidth = 308;
} else {
boxWidth = 400;
}
return boxWidth;
}
function setAspectWidth(type) {
var bw;
if (type) {
bw = 192;
} else {
bw = 100;
}
return bw;
}
function setAspectHeight(type) {
var bh;
if (type) {
bh = 47;
} else {
bh = 100;
}
return bh;
}
我这样访问它们:
function useJcrop(img, type, boxWidth) {
var aspect,
bh = setAspectHeight(type),
bw = setAspectWidth(type),
bWidth =setBoxWidth(type);
}
像这样的
function useJcrop(img, type, boxWidth) {
var aspect,
bh = type ? 308 : 400,
bw = type ? 192 : 100,
bWidth = type ? 47 : 100
}
bh = type ? 47 : 100;
bw = type ? 192 : 100;
bWidth = type ? 308 : 400;
代码要少得多
不过,如果可能的话,我建议您将这些数字放入描述性变量中。或者以编程方式计算它们
function setBoxWidth(type) {
return type ? 308 : 400;
}
function setAspectWidth(type) {
return (type) ? 192 : 100;
}
function setAspectHeight(type) {
return (type) ? 47 : 100;
}
很难比函数更简单。然而,您可能应该考虑将所有这些信息封装在对象中,因为类型在3。/P>之间基本上是共享状态。
function CroppedImage(type)
{
this.type=type;
this.getBoxWidth= function() {
return type ? 308 : 400;
}
/...
}
嗯。。。试试这样的
function useJcrop(img, type, boxWidth) {
var aspect,
bh = type ? 308 : 400,
bw = type ? 192 : 100,
bWidth = type ? 47 : 100
}
bh = type ? 47 : 100;
bw = type ? 192 : 100;
bWidth = type ? 308 : 400;
使这三个函数更有效的最好方法是避免编写它们
function useJcrop(img, type, boxWidth) {
var aspect,
bh = type ? 308 : 400,
bw = type ? 192 : 100,
bWidth = type ? 47 : 100;
}
首先,函数的命名令人困惑。它们不设置任何内容(局部变量除外),而是返回一个值。因此,我将它们称为getFoo()、getBar()等等。此外,您不需要局部变量
function getAspectWidth(type) {
if (type) {
return 192;
} else {
return 100;
}
}
除此之外,我什么也不做。它比你的版本更容易阅读和理解
或者你可以利用
这更简洁。我看不出在哪里为type赋值。对不起,我错了。我做了编辑。这是useJcrop函数中的一个参数。它们必须是函数吗?类型应该是什么类型的值?一个号码?一根绳子?如果它基本上只是用作布尔标志,为什么称它为“type”呢?这个问题似乎是离题的,因为它属于on(或需要澄清)。