从String中引用Object

时间:2013-09-18 12:18:18

标签: javascript arrays object

我有以下一段完美无缺的代码。

但是,我的下面的项目列表将逐渐变成数十个对象,我想知道是否可以删除switch子句并使用更少和更少的代码行。

'type'参数是数组,视口,容器,gridpanel等的类型,'component'参数是数组中的对象本身。

viewport: {},
container: {},
gridpanel: {},
panel: {},
treepanel: {},
window: {},
button: {},

add: function (component, type) {

    switch (component.getType() != undefined ? component.getType() : type) {
        case 'container':
            this.container[component.getId()] = component;
            break;
        case 'gridpanel':
            this.gridpanel[component.getId()] = component;
            break;
        case 'panel':
            this.panel[component.getId()] = component;
            break;
        case 'treepanel':
            this.treepanel[component.getId()] = component;
            break;
        case 'viewport':
            this.viewport[component.getId()] = component;
            break;
        case 'window':
            this.window[component.getId()] = component;
            break;
        case 'button':
            this.button[component.getId()] = component;
            break;
        default:
            break;
    }
},

2 个答案:

答案 0 :(得分:7)

您可以使用bracket notation来引用组件类型:

add: function(component, type) {
    var componentType = component.getType() || type;
    this[componentType][component.getId()] = component;
}

答案 1 :(得分:2)

除了FrédéricHamidi的回答,您可能希望限制要引用的类型数量:

add: function(component, type) {
    var componentType = component.getType() || type;
    if (Ext.Array.indexOf([
        'container', 'gridpanel', 'panel', 'treepanel', 
        'viewport', 'window', 'button'
    ], componentType) !== -1) {
        this[componentType][component.getId()] = component;
    }
}