JavaScript 对象创建
这里是 JavaScript 新手,我在工作中浏览一些 js 代码时遇到了一个用于创建对象的辅助函数,它是这样的,
createElement = function(name, data){
if(name == TYPES.TEXT){
return new Text(data);
}
else if(name == TYPES.WORD){
return new Word(data);
}
else if(name == TYPES.PARAGRAPH){
return new Paragraph(data);
}
else if(name == TYPES.TABLE){
return new Table(data);
}
<list goes on and on and on... >
}
虽然这确实完成了工作,但我想知道是否有更好、更简洁的编写方式这。
JavaScript newbie here, I was going through some js code at work when i came across a helper function for object creation, which went like this
createElement = function(name, data){
if(name == TYPES.TEXT){
return new Text(data);
}
else if(name == TYPES.WORD){
return new Word(data);
}
else if(name == TYPES.PARAGRAPH){
return new Paragraph(data);
}
else if(name == TYPES.TABLE){
return new Table(data);
}
<list goes on and on and on... >
}
while this does get the job done i would like to know if there is a better, cleaner way of writing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,过多的
if..then
或switch
逻辑是 代码味道并且几乎总是可以重构为更优雅的东西。在这种情况下,基于名称的工厂可以重构为字典,其中键作为该名称,值作为返回的函数实时示例: http://jsfiddle.net/KkMnd/
编辑:
createElement
方法中的该行可以/应该首先检查是否为传入的TYPES.*
。一个好的方法是在尝试调用该方法之前检查字典中是否存在元素。You're right, excessive
if..then
orswitch
logic is a code smell and can almost always be refactored into something more elegant. In this case, a factory based upon a name can be refactored into a dictionary with key as that name and value as the function to returnLive example: http://jsfiddle.net/KkMnd/
EDIT: That line in the
createElement
method could/should first check that something is configured for theTYPES.*
passed in. A good way is to check that there is an element in the dictionary before trying to call that method.使用 switch 语句会更清晰一些,但语义上是相同的。
It would be a bit cleaner but semantically the same to use a switch statement.