20 Feb 2024
In JavaScript, there are several ways to create objects. Here are some of the common methods:
-
Object Literal: The simplest way to create an object is by using the object literal notation, which involves enclosing key-value pairs within curly braces
{}.let person = { name: 'John', age: 25, occupation: 'Developer' }; -
Constructor Function: You can create objects using constructor functions, which are functions that initialize and set properties for objects. This method is useful when you need to create multiple similar objects.
function Person(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } let person = new Person('John', 25, 'Developer'); -
Object.create(): The
Object.create()method allows you to create a new object with a specified prototype object.let personPrototype = { greet: function() { console.log('Hello!'); } }; let person = Object.create(personPrototype); person.name = 'John'; person.age = 25; -
Class (ES6+): With the introduction of ECMAScript 6 (ES6), you can use the
classsyntax to create objects with constructors and methods.class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } greet() { console.log('Hello!'); } } let person = new Person('John', 25, 'Developer'); -
Factory Function: Factory functions are functions that return objects. They are useful when you want to create multiple objects with similar properties.
function createPerson(name, age, occupation) { return { name: name, age: age, occupation: occupation }; } let person = createPerson('John', 25, 'Developer');