Ways to Create Objects in JavaScript

04.08.19

There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain other objects

1. Literal notation

var someObject_1 = {};

Perhaps the most common and easiest way. Let's add properties and methods

someObject_1.name = "John";
someObject_1.age = 25;
someObject_1.run = function(){
    console.log("run")
}

And now the same thing, but we will set properties and methods when creating

var someObject_1 = {
    name: "John",
    age: 25,
    run: function(){
        console.log("run");
    }
};

2. Object constructor

This method is not recommended for use, and it is better to use the previous one. Nevertheless, it exists. But the probability of meeting him is extremely small

var someObject_2 = new Object();

We also set properties and methods

var someObject_2 = {
    name: "Nick",
    age: 30,
    jump: function(){
        console.log("jump");
    }
};

3. Function constructor

We can write our constructor function and create objects using the new operator

function SomeObject_3(name, age){
    this.name = name;
    this.age = age;
}
 
SomeObject_3.prototype.run = function(){
    console.log("run");
}

Create an object

var someObject_3 = new SomeObject_3("Alex", 20);

4. Object.create() method

There is another way to create objects - using the Object.create() method. It is not supported in <IE9. The first parameter, the required parameter, is the prototype of the created object, and the second optional parameter is the list of object properties. In order to create an object without a prototype, you must call the Object.create() method with the null parameter.

var someObject_4 = Object.create(Object.prototype);
 
// the full analogue of Object.create (Object.prototype) is
var someObject_4 = {};
 
//object without prototype
var someObject_4 = Object.create(null);

5. Using classes

ES6 syntax provides writing classes in JavaScript. At its core, this is an analog of the third method - using the constructor function. Only with a simpler and clearer record

class SomeObject_4{
     
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
 
    run(){
        console.log("run");
    }
}

Let's create an object, or rather an instance of the class

let someObject_4 = new SomeObject_4("Alex", 20);
blog comments powered by Disqus