如何避免下面代码段中的 if 语句,因为可能有多个 if 需要检查,整个代码看起来会很困惑。是否有可以在这里有效采用的多态机制?此外,请引用链接以了解 javascript 中的多态性(如果有的话)。
function car(type) {
this.type = type;
this.shout = function() {
if(this.type == "automatic")
alert("automatic type");
else if(this.type == "manual")
alert("manual type");
};
}
var audi = new car("manual");
audi.shout();
最佳答案
定义关联数组中的映射:
var carTypes = {};
carTypes["automatic"] = "automatic type";
carTypes["manual"] = "manual type";
然后你可以查找:
this.shout = function() {
alert(carTypes[this.type]);
};
需要进行一些验证以确保数组的键受到约束。
关于Javascript - 如何避免像下面给出的代码片段这样的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467029/