这个用于创建对象的基于构造函数的语法有什么区别:
What is the difference between this constructor-based syntax for creating an object:
person = new Object()...还有这个文字语法:
...and this literal syntax:
person = { property1 : "Hello" };看起来两者都做同样的事情,尽管 JSLint 更喜欢你使用对象字面量表示法.
It appears that both do the same thing, although JSLint prefers you use object literal notation.
哪个更好,为什么?
推荐答案他们都做同样的事情(除非有人做了一些不寻常的事情),除了你的第二个创建一个对象并添加一个财产给它.但是文字符号在源代码中占用的空间更少.可以清楚地识别正在发生的事情,因此使用 new Object(),您实际上只是输入更多内容,并且(理论上,如果没有被 JavaScript 引擎优化)执行不必要的函数调用.
They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.
这些
person = new Object() /*You should put a semicolon here too. It's not required, but it is good practice.*/ -or- person = { property1 : "Hello" };技术上不要做同样的事情.第一个只是创建一个对象.第二个创建一个并分配一个属性.为了让第一个相同,您需要第二个步骤来创建和分配属性.
technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.
某人可以做的不寻常的事情"是隐藏或分配给默认的 Object 全局:
The "something unusual" that someone could do would be to shadow or assign to the default Object global:
// Don't do this Object = 23;在那种非常不寻常的情况下,new Object 会失败,但 {} 会起作用.
In that highly-unusual case, new Object will fail but {} will work.
在实践中,永远没有理由使用 new Object 而不是 {}(除非你做过那件非常不寻常的事情).
In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).
更多推荐
`new Object()` 和对象文字符号有什么区别?
发布评论