How to create Objects in javascript.

There are many methods to create JavaScript objects. But among them 2 are the most popular ones. Below i am going to show you those to you.

  1. Using function constructor
  2. Using Object.create() method

First we will see functional constructor method.
Below is a demonstration of how to crate objects using functional constructor in java script.

<script>
var Person,objCloud,objCloud2;

        Person = function(name = "", email = "") {
          this.name = name;
          this.email = email;
          this.setName = function(name) {
            this.name = name;
           };
          this.getName = function() {
            return 'Your name is : '+this.name;
         };
        };
        
        objCloud = new Person();
        objCloud.setName("Cloud");
        console.log(objCloud.getName());
        objCloud2 = new Person();
        objCloud2.setName("Cloud2");
        console.log(objCloud2.getName());
</script>

This will show result:

Now let us take an example using object.create() method. This one is mostly used for inheritance of objects in java script.

 Person = {
          objNameStr: "Your Name is",
          getName: function() {
            return this.objNameStr +':'+this.name;
          }
        };
        objCloud = Object.create(Person, {
          name: { value: "Cloud WEB Labs" }
        });
        console.log(objCloud.getName());
        objCloud2 = Object.create(Person, {
          name: { value: "Cloud WEB Labs2" }
        });
        console.log(objCloud2.getName());

This will show result:

I hope that it makes sense to you when to use one of them into your java script project.

Thanks you.

Blog Catagory : Blog