What are the possible ways to create objects in Javascript?
1. Object constructor
const myObject = new Object();
The simplest way to create an empty object, but currently this approach is not recommended.
2. Object literal
const myObject = {
name: "Diogo Machado",
country: "Brazil"
}
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces. This is an easiest way to create an object.
3. Function constructor
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// create an object
const person = new Person();
In JavaScript, a constructor function is used to create objects. It is considered a good practice to capitalize the first letter of your constructor function.
4. ES6 Class syntax
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
}
const person = new Person();
ES6 (ECMAScript 6 or ES2015) Javascript introduces class feature to create the objects.
5. Singleton pattern
const singletonService = new (function SingletonService(){
this.name = 'Diogo Machado';
this.age = 31;
}()
A singleton is an object which can be instantiated one time, this pattern is used to encapsulate logical.