2014-01-14 176 views
0

使这三个函数更高效的最佳方法是什么?他们分享逻辑。组合函数以降低复杂性

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

我看不到哪种类型被赋值。 –

+0

对不起,我的错。我做了编辑。这是useJcrop函数中的一个参数。 – webbydevy

+0

他们必须是功能吗? –

回答

0

像这样的事情?

function useJcrop(img, type, boxWidth) { 
    var aspect, 
     bh = type ? 308 : 400, 
     bw = type ? 192 : 100, 
     bWidth = type ? 47 : 100 
} 

这是一个很少的代码。

尽管如此,我建议你把这些数字放入描述性变量中。或以编程方式计算它们。

0
function setBoxWidth(type) { 
    return type ? 308 : 400; 
} 

function setAspectWidth(type) { 
    return (type) ? 192 : 100; 
} 

function setAspectHeight(type) { 
    return (type) ? 47 : 100; 
} 

很难得到比功能简单。你或许应该考虑然而封装所有这些信息中的对象,因为类型基本上是共享状态横跨3

function CroppedImage(type) 
{ 
    this.type=type; 

    this.getBoxWidth= function() { 
     return type ? 308 : 400; 
    } 
    /... 
} 
0

嗯...尝试这样的事情?

bh = type ? 47 : 100; 
bw = type ? 192 : 100; 
bWidth = type ? 308 : 400; 
1

使这三个函数更有效的最好方法是避免编写它们。

function useJcrop(img, type, boxWidth) { 
    var aspect, 
     bh = type ? 308 : 400, 
     bw = type ? 192 : 100, 
     bWidth = type ? 47 : 100; 
} 
0

首先命名你的函数是令人困惑的。他们不设置任何东西(除了局部变量),而是返回一个值。因此我会称它们为getFoo(),getBar()等。此外,你不需要局部变量。

function getAspectWidth(type) { 
    if (type) { 
    return 192; 
    } else { 
    return 100; 
    } 
} 

除此之外,我不会做任何事情。它比你的版本更具可读性和可理解性。

或者你可以利用的ternary operator

function getAspectWidth(type) { 
    return type ? 192 : 100; 
} 

这更加简洁。