Literal notation VS. constructor to create objects in JavaScript [duplicate]
I am learning JavaScript from the basics (although I program in other languages such as C#). It popped up to me the question of which is of this two ways is more efficient and should be use as general rule.
I am sure and expecting no definitive answer but I would like to know the general pros and cons.
Thank you!!
Solution 1:
Object literals are usually the way to go. They only need to be parsed when loading the script, which can introduce various optimizations by the scripting engine.
Constructors need to be executed. That means they will be slower, but you can easily add some validation code etc. to them, and they allow the construction of complex objects with public, privileged methods and private "attributes" hidden in the constructors scope. Also, they of course construct objects that share a prototype, which you might find useful.
Solution 2:
Not aware of any performance efficiency of one over the other. However, the literal notation seems to get its preference due to the simplicity argument, and because it avoids using constructors and new
keyword.
Constructors and the new
keyword are seen by some as negative features of the JavaScript language (see Crockford - JavaScript:The Good Parts). JSLint even calls out when finding new Array()
or new Object()
use.