js Object

In JavaScript, objects are fundamental building blocks that allow you to store collections of data and more complex entities. Objects consist of properties and methods, representing state and behavior, respectively.

Introduction to JavaScript Objects

Definition: An object in JavaScript is a collection of properties and methods. A property is a key-value pair, and a method is a function associated with the object.

Example Entities: Car, pen, bike, chair, glass, keyboard, and monitor can all be represented as objects with various properties (e.g., color, size) and methods (e.g., start, stop).

JavaScript Objects: Object-Based Language

JavaScript is an object-based language, meaning that most of the programming constructs are objects. Unlike class-based languages, JavaScript uses a prototype-based approach, where objects inherit properties and methods directly from other objects.

Creating Objects in JavaScript

1. By Object Literal

An object literal is a comma-separated list of key-value pairs enclosed in curly braces {}. This is a straightforward way to create an object.

Example:

var car = {
brand: "Toyota",
model: "Camry",
year: 2021,
start: function() {
document.write("Car started");
}
}; document.write(car.brand);
car.start();

Output:

Toyota
Car started

2. By Creating an Instance of Object Directly

You can create an object instance using the Object constructor with the new keyword. This method creates a generic object.

var bike = new Object();
bike.brand = "Honda";
bike.model = "CBR600";
bike.year = 2020;
bike.start = function() {
document.write("Bike started");
};
document.write(bike.brand);
bike.start();

Output:

Honda
Bike started

3. By Using an Object Constructor

You can define a constructor function and then create objects using the new keyword with this constructor. This is useful for creating multiple objects with similar structures.

Example:

function Chair(color, material) {
this.color = color;
this.material = material;
this.describe = function() {
document.write(`This is a ${this.color} chair made of ${this.material}.`);
};
}

var officeChair = new Chair("black", "leather");
var diningChair = new Chair("brown", "wood");

officeChair.describe();
diningChair.describe();

Output:

This is a black chair made of leather.
This is a brown chair made of wood.