JavaScript OOP Basics
What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. Objects can contain data (properties) and code (methods). JavaScript supports OOP through features like constructor functions, prototypes, and ES6 classes.
Key Concepts in JavaScript OOP
- Constructor Functions: Functions used to create objects and initialize their properties.
- Prototypes: Objects that provide shared methods and properties for instances.
- Classes: ES6 syntax for defining objects and their behavior in a more structured way.
- Instances: Objects created using constructor functions or classes.
Example: Constructor Function
function User(username, email) {
this.username = username;
this.email = email;
this.print = function () {
console.log(this.email, this.username);
};
}
let user = new User("DeathCode", "dc@dc.com");
let user2 = new User("DeathCode2", "dc2@dc.com");
console.log(user);
console.log(user2);Explanation:
function User: Defines a constructor function.this.usernameandthis.email: Set properties for each instance.new User(): Creates an instance of theUserobject.
Prototypes
Prototypes allow you to share methods between instances without duplicating them in memory.
User.prototype.greet = function() {
console.log(`Hello, ${this.username}!`);
};
user.greet(); // Hello, DeathCode!
user2.greet(); // Hello, DeathCode2!Explanation: User.prototype.greet adds a method to the prototype, making it available to all instances of User.
Classes
ES6 introduced class syntax to make OOP in JavaScript more intuitive.
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
print() {
console.log(this.email, this.username);
}
greet() {
console.log(`Hello, ${this.username}!`);
}
}
let user3 = new User("DeathCode3", "dc3@dc.com");
user3.print(); // dc3@dc.com DeathCode3
user3.greet(); // Hello, DeathCode3!Explanation:
constructor: A special method for initializing object properties.printandgreet: Methods defined within the class.
Instances and this Keyword
The this keyword refers to the instance of the object that is calling the method.
user.print(); // dc@dc.com DeathCode
user2.print(); // dc2@dc.com DeathCode2Conclusion
JavaScript's OOP features provide a powerful way to structure your code and reuse functionality. Understanding constructor functions, prototypes, and classes is essential for writing efficient and maintainable JavaScript applications.