Different Ways to Create Objects in JavaScript
JavaScript has a number of predefined objects. In addition, you can create your own objects.
Using object initializers#
It is sometimes referred to as creating objects with literal syntax. It’s one of easiest way to create an object by simply define the property and values inside curly braces.
let product = {
mfgCountry: 'Indonesia'
};
product.name = 'Surgical Mask';
product.category = 'medical';
Using Object class#
let product = new Object(); // store an empty Object object in product.
product.name = 'Surgical Mask';
product.category = 'medical';
product.mfgCountry = 'Indonesia';
Using Object’s create method#
// Create a new object using an existing object as the prototype.
let product = Object.create({
name: this.name,
category: this.category,
mfgCountry: 'Indonesia'
}, {
name: { value: 'Surgical Mask' },
category: { value: 'medical' },
});
Using Object.prototype.constructor function#
function Product(name, category) {
this.name = name;
this.category = category;
this.mfgCountry = 'Indonesia';
}
let product = new Product('Surgical Mask', 'medical');
console.log('product.constructor is ' + product.constructor);
Using ES6 Class syntax#
JavaScript classes are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance.
class Product {
constructor(name, category) {
this.name = name;
this.category = category;
this.mfgCountry = 'Indonesia'
}
}
let product = new Product('Surgical Mask', 'medical');
Using Immediately Invoked Function Expression (IIFE)#
IIFE is a design pattern which is also known as a self-executing anonymous function.
let product = new(function (name, category) {
this.name = name;
this.category = category;
this.mfgCountry = 'Indonesia';
})('Surgical Mask', 'medical');
Using Function constructor with prototype#
(Note: this is NOT one of the way to create a JavaScript object with the same behavior as the rest of the examples in this post because it set the property on the prototype and not the object it self.)
function Product() {
this.mfgCountry = 'Indonesia';
}
Product.prototype.name = 'Surgical Mask';
Product.prototype.category = 'medical';
let product = new Product();
I deliberately show this example because this is where a lot of confusion usually begins with JavaScript prototypes.