Google News
logo
5 Different Ways to Create Objects in JavaScript
Free Time Learning

Publisher : Meck Charles


5 Different Ways to Create Objects in JavaScript

In JavaScript, there are several ways to create objects. Here are some of the most commonly 5 ways :
1. Object Literal Notation : This is the simplest way to create an object. You can use curly braces to define an object and add properties and methods.

const person = {
  name: "John",
  age: 30,
  sayHello: function() {
    console.log("Hello");
  }
};​
2. Constructor Function : You can create objects using a constructor function. This is similar to creating classes in other languages.

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    console.log("Hello");
  }
}

const person = new Person("John", 30);​
3. Object.create() Method : You can use the Object.create() method to create an object with a specified prototype.

const personProto = {
  sayHello: function() {
    console.log("Hello");
  }
};

const person = Object.create(personProto);
person.name = "John";
person.age = 30;​

4. ES6 Classes :
You can use ES6 classes to create objects. This is similar to using constructor functions but with a more concise syntax.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
 
  sayHello() {
    console.log("Hello");
  }
}

const person = new Person("John", 30);​
5. Singleton Pattern : You can create a singleton object using a self-invoking function. This pattern ensures that only one instance of an object is created.

const singleton = (function() {
  let instance;
 
  function createInstance() {
    const object = new Object("Object instance");
    return object;
  }
 
  return {
    getInstance: function() {
      if(!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const instance1 = singleton.getInstance();
const instance2 = singleton.getInstance();

console.log(instance1 === instance2); // true​

Conclusion :
These are just a few of the many ways to create objects in JavaScript. The best method to use will depend on the specific needs of your application.
LATEST ARTICLES