Creating object using Object class

In the previous post we learned that Javascript is an object oriented language and there are several ways to create objects in javascript. The first one we discussed was using the Object Literal. In this post we are going to discuss another approach to create object by using Object class.

Object class is an in-built class in Javascript. All the objects in javascript inherit this class.

Let’s see an example of creating an object using Object class:


In the above example you can see that on line 2 , person1 object is created using Object() class constructor . We have defined a property “name” and a method “print” of the person1 object. person1 also inherits the properties and methods from the Object class. person1 can use these methods as they are defined in the object class or it can override the definition of these methods.

For example : toString() method in Object class returns the string representation of the object. But if we want to redefine it and change its functionality we can do that. Let’s look at the example below:

John //print() method output
Rufert // toString() method output

As you can see in the example above we have given our own definition of the toString() method and it prints the last_name property of the person1 object.

This was all about creating an object using Object class. We will learn about the third approach of creating object using constructor function in the next post.