如下面的代码片段所示,如何避免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]);
};
需要进行一些验证以确保数组的键受到约束。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句