javascript - 在 Javascript 中实现多态性——这看起来怎么样?

标签 javascript polymorphism

我正在尝试跳转到更 OOP 风格的 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
        });
    });
}

关于javascript - 在 Javascript 中实现多态性——这看起来怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30648017/

相关文章:

javascript - 如何正确地将嵌入式 ruby​​ 代码放入 JavaScript?

c++ - 同时处理基类的多个指针时如何处理多态性?

c# - NullReferenceException 引用基类派生成员对象的公共(public)成员

c++ - 为什么一个虚类的析构函数没有自动添加到虚表中?

javascript - 在 JavaScript 函数中获取 Json 数组值

javascript - 继承angularJS模块

javascript - React js 我应该如何处理在调用 componentDidMount() 之前使用的对象?

javascript - 如何允许我的 Asp.net MVC 3 Web 应用程序使用 MathJax 接受用户输入 $x<y>z$?

c# - 调用没有反射的方法声明

java - MVC : How do I reduce the amount of polymorphic methods?