Skip to content

Instantly share code, notes, and snippets.

@AlexRogalskiy
Last active September 13, 2020 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexRogalskiy/3c1aa144652690d74dec8f9f971083a2 to your computer and use it in GitHub Desktop.
Save AlexRogalskiy/3c1aa144652690d74dec8f9f971083a2 to your computer and use it in GitHub Desktop.
JS object creation strategies

Different ways to create objects in JavaScript

JavaScript has a number of predefined objects. In addition, you can create your own objects.

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';
let product = new Object(); // store an empty Object object in product.
product.name = 'Surgical Mask';
product.category = 'medical';
product.mfgCountry = 'Indonesia';
// 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' },
});
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);

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment