JavaScript Objects
Objects are one of the most important concepts in JavaScript. They allow developers to group related data and functionality together, making code more organized and expressive. In JavaScript, an object is essentially a collection of properties (key-value pairs), where values can be data or functions (methods).
🌍 What Is an Object?
- An object is a standalone entity with properties and type.
- Properties are associations between a key (string) and a value (any data type).
- If a property’s value is a function, it is called a method.
Mozilla Developer
// Example of an object
const person = {
name: "Alice",
age: 25,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.name); // Alice
console.log(person.greet()); // Hello, my name is Alice
🛠️ Creating Objects
Object Literals
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
Using new Object()
const book = new Object();
book.title = "1984";
book.author = "George Orwell";
Constructor Functions
function Animal(type) {
this.type = type;
}
const dog = new Animal("Dog");
Classes
class Student {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
const s1 = new Student("Bob", 101);
🔄 Object Properties and Methods
- Accessing properties:
object.propertyorobject["property"] - Adding properties:
object.newProp = value - Deleting properties:
delete object.prop - Methods: Functions stored as property values.
TutorialsPoint
const phone = {
brand: "Apple",
call: function(number) {
return `Calling ${number}...`;
}
};
console.log(phone.call("123456789")); // Calling 123456789...
✨ The this Keyword
Inside an object method, this refers to the object itself.
const person = {
name: "Alice",
greet: function() {
return `Hi, I am ${this.name}`;
}
};
console.log(person.greet()); // Hi, I am Alice
📊 Comparison Table
| Feature | Description | Example |
|---|---|---|
| Object Literal | Quick way to define an object | {name: "Alice"} |
| Constructor Function | Function used to create objects | new Animal("Dog") |
| Class | ES6 syntax for object blueprints | class Student {} |
| Method | Function inside an object | person.greet() |
📖 Conclusion
JavaScript objects are the backbone of the language, enabling developers to structure data and behavior together. With properties, methods, and flexible creation patterns (literals, constructors, classes), objects make JavaScript powerful and expressive.
No comments:
Post a Comment