Skip to content

Commit a5e162d

Browse files
committed
feat: add POO explanations
1 parent 864896f commit a5e162d

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

advanced/object_oriented.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 📌 JavaScript Intermediate - Object-Oriented Programming (OOP)
2+
3+
// Welcome to the sixth section of the JavaScript Intermediate tutorial!
4+
// Here, you'll learn about Object-Oriented Programming (OOP) in JavaScript.
5+
6+
// Constructor Function
7+
function Person(name, age) {
8+
this.name = name;
9+
this.age = age;
10+
this.greet = function () {
11+
console.log(
12+
`Hello, my name is ${this.name} and I am ${this.age} years old.`
13+
);
14+
};
15+
}
16+
const person1 = new Person("Alice", 25);
17+
person1.greet();
18+
19+
// Classes (ES6+)
20+
class Animal {
21+
constructor(name, sound) {
22+
this.name = name;
23+
this.sound = sound;
24+
}
25+
makeSound() {
26+
console.log(`${this.name} says ${this.sound}`);
27+
}
28+
}
29+
const dog = new Animal("Dog", "Woof");
30+
dog.makeSound();
31+
32+
// Inheritance
33+
class Dog extends Animal {
34+
constructor(name, breed) {
35+
super(name, "Woof");
36+
this.breed = breed;
37+
}
38+
showBreed() {
39+
console.log(`${this.name} is a ${this.breed}.`);
40+
}
41+
}
42+
const myDog = new Dog("Buddy", "Golden Retriever");
43+
myDog.makeSound();
44+
myDog.showBreed();
45+
46+
// Getters and Setters
47+
class User {
48+
constructor(username) {
49+
this._username = username;
50+
}
51+
get username() {
52+
return this._username;
53+
}
54+
set username(newUsername) {
55+
this._username = newUsername;
56+
}
57+
}
58+
const user = new User("JohnDoe");
59+
console.log(user.username);
60+
user.username = "JaneDoe";
61+
console.log(user.username);
62+
63+
// 💡 Practice using OOP principles to structure your JavaScript applications!

0 commit comments

Comments
 (0)