Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal notation VS. constructor to create objects in JavaScript [duplicate]

Tags:

javascript

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!!

like image 562
Julen Avatar asked Sep 10 '12 17:09

Julen


People also ask

When would you create an object using literal notation vs constructor notation?

Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.

What is the difference between creating an object using literal notation and creating an object using a constructor?

The main difference here is what you can do with it. With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.

What is the main advantage of using constructor functions over object literals?

Object defined with a function constructor lets you have multiple instances of that object. This means change made to one instance, will not affect other instances.

What is a literal constructor in JavaScript?

Constructor vs Object Literal An object literal is typically used to create a single object whereas a constructor is useful for creating multiple objects: //Object literal let user = { name: 'Bob' } //Constructor function User() { this.name = 'Bob'; } var user1 = new User(); var user2 = new User();


1 Answers

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.

like image 131
Bergi Avatar answered Oct 06 '22 23:10

Bergi