4 Ways JavaScript Object Instantiation

wahyu eko hadi saputro
2 min readMay 24, 2022

If you are a programmer, you must be familiar with objects. Object is an instance of class, and class is the blueprint / design of an object. For example if we want to build a house, we will hire an architect to design our house, and after that we start building the house. We call the design of the house with class, and we call the house building with objects.

By default if we create any variable or function, it will be a global variable / function. Global means that the variable / function is on window object scope, to inspect any variable or function on window object, just use command : console.log(this)

list of global function and variable (window scope)

There are different ways to create new objects in javascript:
1. Create a single object, using an object literal.
2. Create a single object, with the keyword new.
3. Define an object constructor, and then create objects of the constructed type.
4. Create an object using Object.create().

  1. Create a single object, using an object literal.
const employee = {
firstName: "John",
lastName: "lenon",
fullName : function() {
console.log(this)
return this.firstName + " " + this.lastName;
}
};

employee.fullName();

2. By using new keyword

const student = new Object();
student.name = "lucifer"
console.log(student.name)

3. Create an object using Object.create()

// Animal properties and method encapsulation
const Animal = {
type: 'Invertebrates', // Default value of properties
displayType: function() { // Method which will display type of Animal
console.log(this.type);
}
};
// Create new animal type called animal1
const animal1 = Object.create(Animal);
animal1.displayType(); // Output: Invertebrates

4. Define an object constructor, and then create objects of the constructed type.

class Polygon {
constructor() {
this.name = 'Polygon';
}
}
const poly1 = new Polygon();
console.log(poly1.name);
// expected output: "Polygon"

--

--