Objects are generally Non-Primitive Data Types.
Objects in JavaScript are collections of key-value pairs, where the keys are properties and the values can be any data type. They represent real-world entities or concepts.
Objects are commonly used to represent the data structures, encapsulate properties and methods, and model real-world entities. They are essential for building complex real-word JavaScript applications.
- Object properties and methods
- Object creation
- Constructors
- Methods
- Properties
- Inheritance
- Polymorphism
- this keyword
- Prototype inheritance
Properties: Key-value pairs that define the characteristics of an object. Methods: Functions defined within an object that operate on its properties.
- Literal notation:
let person = {
name: "kumar",
age: 30,
greet: function() {
console.log("Hello!");
}
};
- Constructor function:
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person("kumar", 30);
It is one type of functions used to create objects. It typically use the this keyword to initialize object properties.
It is one type of functions defined within an object. It can access and modify the object properties.
It is a key-value pairs that store data within an object.
Inheritance is a mechanism in object-oriented programming that allows to inherit properties and methods from one object (parent or base object) to another object (child or derived object).
Syntax:
class ChildClass extends ParentClass {
// Constructor
constructor() {
super(); // Call the parent class's constructor
// Additional properties or methods
}
}
class Employee {
constructor(name) {
this.name = name;
}
details() {
console.log("Details of Employee");
}
}
class Manager extends Employee {
details() {
console.log("Name: " + this.name);
}
}
let manager = new Manager("Kumar");
manager.details();
Polymorphism is the ability of objects to respond to the same method call in different ways.
Syntax: (Overriding methods)
class ChildClass extends ParentClass {
// Override the parent class's method
method() {
// Custom implementation
}
}
class Employee {
constructor(name) {
this.name = name;
}
details() {
console.log("Details of Employee");
}
}
class Manager extends Employee {
details() {
console.log("Name: " + this.name);
}
}
let manager = new Manager("Kumar");
manager.details();
This refers to the current object within a method.
Prototype Inheritance means that objects created using a constructor function inherit properties and methods from the constructor prototype.
Prototype: An object that serves as a template for other objects.
Creating custom prototypes: Syntax: (Modifying the prototype)
Object.prototype.myCustomMethod = function() {
// Method implementation
};
Syntax: (Creating a custom prototype object)
function MyObject() {}
MyObject.prototype.myProperty = "value";
MyObject.prototype.myMethod = function() {
// Method implementation
};