What are object literals?

In simple language when you use many key and value pairs by separating them with a comma inside the curly brackets then it is known as object literals.

What is an object

The variable which you use for object literal is known as object further more information the key-value pairs which you use inside the curly braces are known as object properties.

What are Constructor and ‘this’ Keywords

Now you know what is an object and object literals so I am going to tell you about the constructor so if you will use only object literals you can only define the properties of one variable.

Example: const John {

firstName : ‘John’
lastName : ‘ Doe’
age : ‘ 30’
}

Basically, the constructor is defined as a function and you have to give it an instance and have to pass the argument in the function parenthesis and then inside of that function, you have to use that argument of instance by adding it with ‘this’ keyword in front of it.

What ‘ this ‘ keyword refers is to what is the instance of the object.

Outside of the function, you have to define some object variables then in the value of that variable you have to add new with the instance and then have to put the value inside the parenthesis.

For clearing your doubt I gave an examplebelow have a look at it

Example function Person( name) {

this.name : ‘ name’
this.name : ‘ name’
}

const john = new Person( ‘ John’)
const steve = new Person ( ‘ Steve’)

Build In Constructors

This is not recommended because it slows down your website but you may need to use it sometime.

If you want to change your primitive type, functions into an object there are certain object constructor which can do it for you.

Here is nothing much you just have to use new and add it with the primitive type which you have to do the same for function.

And you also use the new object for the objects but it will show you the same results as the object does.

misterishaan
misterishaan
Articles: 47