在Javascript中实现多态性——会是什么样子?

Implementing Polymorphism in Javascript - how would this look?

本文关键字:什么样 实现 多态性 Javascript      更新时间:2023-09-26

我试图使跳转到一个更面向对象风格的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代表对象的顶部和左侧位置?

我会创建一个对象,您可以在其中查找保存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
        });
    });
}