2015-06-04 37 views
0

我試圖讓跳轉到更多的OOP風格的JavaScript方法,但我只是沒有得到它在JavaScript的權利。在Javascript中實現多態 - 這看起來如何?

以下面的函數爲例。

function positionalCSS(array, cs, lcs){ 
/* Define css for circle based on number of circles */ 
//Count array 
var arrCount = array.length; 
var T = []; 
var L = []; 
if(arrCount == 3){ 
    T[0] ='15px'; 
    L[0] = '240px'; 
    T[1] = '345px'; 
    L[1] = '440px'; 
    T[2] = '345px'; 
    L[2] = '40px'; 
} 
if(arrCount == 4){ 
    T[0] ='-135px'; 
    L[0] = '90px'; 
    T[1] = '-10px'; 
    L[1] = '290px'; 
    T[2] = '220px'; 
    L[2] = '270px'; 
    T[3] = '315px'; 
    L[3] = '90px'; 
} 
if(arrCount == 6){ 
    T[0] ='-135px'; 
    L[0] = '90px'; 
    T[1] = '-10px'; 
    L[1] = '290px'; 
    T[2] = '220px'; 
    L[2] = '270px'; 
    T[3] = '315px'; 
    L[3] = '90px'; 
    T[4] = '210px'; 
    L[4] = '-100px'; 
    T[5] = '-10px'; 
    L[5] = '-110px'; 
} 
$.each(array, function(i) { 
    var num = parseInt(i); 
    // console.log('$("' + lcs + ' ' + cs + '.handle-' + num + '").first().children("div");'); 
     $(lcs + ' ' + cs + '.handle-' + num).first().children('div').css({ 
     'position': 'absolute', 
     'top': T[num], 
     'left': L[num] 
    }); 
}); 

}

這幾乎可怕的,我想在一個數組來傳遞,而這取決於有多少,組織在此基礎上的項目的位置。所以我想基於它的大小,我會給它一些屬性?每個TL代表一個對象的頂部和左側位置?

回答

1

我會創建一個對象,您可以在其中查找預製的對象數組,以保存您的T/L值。

var counts = { 
    3: [ 
    {t:'15px', l:'240px'}, 
    {t:'345px', l:'440px'}, 
    {t:'345px', l:'40px'} 
    ], 
    4: { 
    // as above 
    }, 
    5: { 
    // as above 
    } 
}; 

,然後用它在你的函數:

function positionalCSS(array, cs, lcs){ 
    $.each(counts[array.length], function(i, obj) { 
     // console.log('$("' + lcs + ' ' + cs + '.handle-' + i + '").first().children("div");'); 
     $(lcs + ' ' + cs + '.handle-' + i).first().children('div').css({ 
      'position': 'absolute', 
      'top': obj.t, 
      'left': obj.l 
     }); 
    }); 
} 
+0

做,感謝幫助的極好途徑! –

+0

不客氣。 –

相關問題