JavaScript Objects
JavaScript objects are collections of key-value pairs, where the keys are strings and the values can be of any type. They are fundamental in JavaScript for organizing and managing data.
1. Creating Objects
You can create objects using object literals or the Object
constructor.
Object Literal
const person = {
name: "John",
age: 30,
greet: function() {
return "Hello, " + this.name;
}
};
Here, person
is an object with properties name
, age
, and a method greet
.
Object Constructor
const person = new Object();
person.name = "John";
person.age = 30;
person.greet = function() {
return "Hello, " + this.name;
};
This method is less common but demonstrates how you can add properties to an object created with the Object
constructor.
2. Accessing and Modifying Object Properties
You can access and modify object properties using dot notation or bracket notation.
Dot Notation
console.log(person.name); // "John"
person.age = 31;
Bracket Notation
console.log(person["name"]); // "John"
person["age"] = 31;
3. Object Methods
Object methods are functions that are properties of an object. They can be defined using either traditional function syntax or ES6 arrow functions.
Traditional Method
const person = {
name: "John",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // "Hello, John"
ES6 Method
const person = {
name: "John",
greet() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // "Hello, John"
4. The this
Keyword
this
refers to the current object in method calls. It allows access to the object's properties and methods from within the method itself.
const person = {
name: "John",
greet() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // "Hello, John"
5. Object Prototypes
JavaScript objects have a prototype chain that allows them to inherit properties and methods from other objects.
// Creating a prototype
const animal = {
eats: true
};
// Creating an object that inherits from animal
const dog = Object.create(animal);
console.log(dog.eats); // true
In this example, dog
inherits the eats
property from the animal
prototype.