Methods of constructing objects
Object construction methods in JavaScript
Objects in JavaScript serve as the fundamental building blocks for combining data and behavior (methods). Before the introduction of the ES6 class
syntax, developers created objects using various methods such as object literals, factory functions, constructor functions, and Object.create(). In this section, we will analyze these methods at the engine level and demonstrate when to use each.
The simplest and most common way to create an object. Suitable for simple data or one-time use.
const user = { name: 'Anna', greet() { console.log(`Hi, I'm ${this.name}`); } };
user.greet(); // Hi, I'm Anna
Internal Structure: The JavaScript engine creates a new object whose [[Prototype]]
points to Object.prototype
.
Advantages:
Disadvantages:
A regular function that returns a new object. Provides control and abstraction without the new
keyword.
function createUser(name) { return { name, greet() { console.log(`Hello, ${this.name}`); } }; }
const user1 = createUser('Ani'); const user2 = createUser('Karen');
Advantages:
new
or this
Disadvantages:
As a solution, methods can be placed in the prototype, but this already resembles a constructor function.
Before the introduction of class
, this was the primary way to create objects resembling "classes."
function User(name) { this.name = name; }
User.prototype.greet = function() { console.log(Hello, ${this.name}); };
const u1 = new User('Narek');
Internal Process:
User.prototype
this
is bound to that object
Advantages:
Disadvantages:
new
, otherwise this
will reference incorrectlyThis method creates a new object whose [[Prototype]]
points to the specified object. Ideal for fine-grained inheritance.
const userProto = { greet() { console.log(`Hi, I'm ${this.name}`); } };
const user = Object.create(userProto); user.name = 'Mariam'; user.greet(); // Hi, I'm Mariam
Advantages:
Object Delegation
Disadvantages:
JavaScript offers multiple ways to create objects, each serving different purposes. At the engine level, all of them ultimately create an object, but they differ in terms of prototype linkage, method placement, memory efficiency, and control.
In the next section, we will discuss the ES6 class
syntax—how it is merely syntactic sugar and how it translates at the engine level.