2014-01-14 177 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; 
} 

這更加簡潔。