Objects In JavaScript:

Object Literal:
The object literal syntax allows you to create an object directly by specifying its properties and values using curly braces.


javascript
const person = { name"John"age25occupation"Software Developer", };


Real-life example: Creating a person object with properties like name, age, and occupation to represent a software developer.


Object Constructor:
JavaScript provides a built-in Object constructor function that can be used to create objects. You can create an object using the new keyword and the Object constructor.


javascript
const car = new Object(); car.make = "Toyota"; car.model = "Camry"; car.year = 2021;


Real-life example: Creating a car object by setting properties like make, model, and year to represent a Toyota Camry from 2021.


Factory Functions:
Factory functions are functions that return an object when invoked. You can define a function that creates and returns an object with the desired properties.

javascript
function createPerson(name, age, occupation) { return { name: name, age: age, occupation: occupation, }; } const person = createPerson("Jane", 30, "Teacher");

Real-life example: Creating a person object by invoking the createPerson factory function and passing the person's name, age, and occupation to represent a teacher named Jane.

Constructor Functions (ES5):
Constructor functions are used to create objects with the new keyword. You define a function that serves as a blueprint for creating objects, and properties can be assigned using the this keyword.

javascript
function Person(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } const person = new Person("Alice", 35, "Doctor");

Real-life example: Creating a person object by using the Person constructor function and providing values for the person's name, age, and occupation to represent a doctor named Alice.

ES6 Classes:
ES6 introduced the class syntax, which provides a cleaner and more familiar way to define objects. Classes serve as blueprints for creating objects, and you can define properties and methods within the class.

javascript
class Book { constructor(title, author) { this.title = title; this.author = author; } display() { console.log(`${this.title} by ${this.author}`); } } const book = new Book("The Great Gatsby", "F. Scott Fitzgerald"); book.display();

Real-life example: Creating a book object using the Book class and providing the book's title and author. The display method can be used to show information about the book.

Comments