Javascript约定:对象构造函数中的switch语句
我想知道我的方法在这种情况下是否有效/最佳实践: 我在Angle factory中构建了一个这样的标记。我没有为每种类型扩展标记,而是使用一个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
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)更“简单”