为什么 Object.create() 如此冗长?
Object.create 是对 JavaScript 的一个很好的补充,因为它遵循更多的是 JS 的原型性质。然而,我忍不住发现函数的第二个参数的语法太冗长了,并且退了一步。
例如,如果我想创建一个对象,并在派生对象中指定一个新属性,我需要在属性对象中包含该属性值,无论我是否对额外功能感兴趣。
所以,像这样简单的事情:
o = Object.create({}, { p: 42 })
现在变成:
o = Object.create({}, { p: { value: 42 } })
显然这是一个简单的例子,但对我来说,冗长的内容是不必要的,并且应该是可选的。
有人理解需要属性对象的决定吗?您对新语法的要求有何看法?
注意:我知道有一些简单的解决方案可以克服这一要求。
Object.create is a great addition to JavaScript, because it adheres more to the prototypical nature of JS. However, I can't help but find the syntax of the 2nd parameter to the function to be too verbose, and a step back.
For example, if I want to create an object, and specify a new property in the derived object, I need to include that property value within a property object, regardless if I'm interested in the extra features or not.
So, something as simple as this:
o = Object.create({}, { p: 42 })
Now becomes:
o = Object.create({}, { p: { value: 42 } })
Obviously this is a simple example, but to me the verbosity is unnecessary, and should be optional.
Does anyone understand the decision to require a properties object? What is your opinion of the requirement of the new syntax?
Note: I understand there are easy solutions to overcome this requirement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
语法是这样完成的,以便您可以添加控制每个属性的参数:
因此,当您这样做时:
您是在说您想要一个名为
p
且值为42< 的属性/代码>。这里的关键是,您可以为每个属性设置其他参数,如果没有这个额外的对象层次结构,您将没有任何方法来传递这些额外的参数。
例如,您也可以这样做:
您不仅指定
42
的值,还指定该属性的一些选项。如果这里没有额外的对象层次结构,那么您就没有地方放置这些额外的选项。是的,当您只想要简单的情况时,这确实看起来很不方便。但是,您可以轻松地自己编写一个帮助函数,使更简单的语法发挥作用:
此处演示:http://jsfiddle。网/jfriend00/vVjRA/
The syntax is done this way so that you can add parameters that control each property:
So, when you do this:
you are saying that you want a property named
p
with a value of42
. The key here is that there are other parameters you can set for each property and if there wasn't this extra level of object hierarchy, you wouldn't have any way to pass those extra parameters.So, for example, you could also do this:
Here's you are not just specifying the value of
42
, but also some options for that property. If there wasn't the extra level of object hierarchy here, then you wouldn't have a place to put those extra options.Yes, it does seem inconvenient when you only want the simple case. But, you could easily write yourself a helper function that made the simpler syntax work:
Demo here: http://jsfiddle.net/jfriend00/vVjRA/