Javascript约定:对象构造函数中的switch语句

时间:2014-03-08 12:31:53

标签: javascript angularjs object switch-statement

我想知道我的方法对于这种情况是有效的/最佳实践: 我在角形工厂里建造了这样的标记。我没有为每种类型扩展标记,而是使用切换语句来切换标记的类型。该类型确定标记的图标。

engine.factory('marker', ['map', function (map) {

 return function constructMarker(position, id, type) {

this.id = id;
this.position = position;

switch (type) {
  case 'assigned':
    this.icon = greenMarker;
    break;
  case 'unassigned':
    this.icon = redMarker;
    break;
  default:
    throw new Error(type + 'is an invalid marker type');
    break;
  }

    return L.marker(this.position, {icon: this.icon}).addTo(map.layers[type]);
  };
}]);

日Thnx

1 个答案:

答案 0 :(得分:1)

这一点更优雅:

engine.factory('marker', ['map', function (map) {
    return function constructMarker(position, id, type) {
        var types = {
            'assygned':{
                icon: greenMarker
            },
            'unassigned':{
                icon: redMarker
            }     
        }

        if(!types[type]){
            throw new Error(type + 'is an invalid marker type');
        }

        this.id = id;
        this.position = position;    

        return L.marker(this.position, {icon: types[type].icon}).addTo(map.layers[type]);
    };
}]);