Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript约定:对象构造函数中的switch语句_Javascript_Angularjs_Object_Switch Statement - Fatal编程技术网

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

Javascript约定:对象构造函数中的switch语句,javascript,angularjs,object,switch-statement,Javascript,Angularjs,Object,Switch Statement,我想知道我的方法在这种情况下是否有效/最佳实践: 我在Angle factory中构建了一个这样的标记。我没有为每种类型扩展标记,而是使用一个switch语句来切换标记的类型。该类型确定标记的图标 engine.factory('marker', ['map', function (map) { return function constructMarker(position, id, type) { this.id = id; this.position = position; swi

我想知道我的方法在这种情况下是否有效/最佳实践: 我在Angle factory中构建了一个这样的标记。我没有为每种类型扩展标记,而是使用一个switch语句来切换标记的类型。该类型确定标记的图标

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

这一款稍微优雅一点:

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]);
    };
}]);

@user3396016至少在您的情况下,此语法比
switch case
syntax(imho)更“简单”