JavaScript Object Constructor With Example

Objects in JavaScript

JavaScript is an Object Oriented Programming (OOP) language. A programming language is called object-oriented if it has the following four basic capabilities: encapsulation, aggregation, inheritance and polymorphism. All The objects will have properties and methods.

The Object() Constructor

A constructor is a function that creates and initializes an object. The Object() constructor is used to build an object. The return value of the Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned to the object are not variables. These properties can be accessed only through objects.

Syntax to access the properties:

   Objectname.property

Example: Creating an object


Result:


   Book name is : Coding for world
   Book author is : aimtocode

Defining methods for an Object

Methods can be created using the objects.

Example: Adding a function along with an object

Result:

 
   Book title is : Coding for world
   Book author is : Pvpn
   Book price is : 400
 

In the above example, two methods are used. Book() is a constructor. So it does not need any object to access it.

addPrice() is a user defined method. It has to be accessed through an object.



Read In Details: