🎩 JavaScript Classes

🎩 JavaScript Classes

Modern JavaScript and Object-Oriented Programming

(A special edition that even makes people who say “OOP is boring” fall in love — )

For years, JavaScript walked around saying,
“I’m actually prototype-based, I don’t have classes, get used to me like this.”
But then ES6 came along and said:

“Nobody understands you like this. Let’s give you a proper class structure.”

And from that moment on, JavaScript libraries, frameworks, and game engines became much more organized.

Today, together we will learn:

  • What is a class?
  • What does the constructor do?
  • What are methods, getters, and setters used for?
  • How does inheritance work?
  • What is the purpose of static?
  • How do you use private fields?
  • How to create realistic examples like game characters?
  • What are the professional tips?

We’re going to learn all of this in a fun, charming, and super educational way.

Let’s begin, baby. 🤌💛


💛 1) What is a Class? (Once you understand this logic, everything else clicks)

A class = a template for creating objects.
Think of it like baking multiple cakes using one recipe.
Recipe → class
Each cake → instance (object)

You can create objects with functions in JavaScript,
but classes make everything:

  • More organized
  • More readable
  • More object-oriented
  • More professional

🔧 A simple class:

class Player {
  constructor(name, level) {
    this.name = name;
    this.level = level;
  }
}

But this is too plain…
We are going to turbo-charge it. 💨


💛 2) constructor(): The Birth of an Object

The constructor = the function that runs the moment the object is born.

It:

  • Sets default values
  • Defines properties
  • Builds the identity of your object

Example:

class Player {
  constructor(name, level = 1, hp = 100) {
    this.name = name;
    this.level = level;
    this.hp = hp;
  }
}

const hero = new Player("Cansu", 42);
console.log(hero);

💡 Pro Tip:

You must use this inside a constructor.
this → refers to the new object being created.

If you ask, “But what is this?”
It’s like the hand holding your coffee… but in code 😌


💛 3) Methods: The Superpowers of an Object

A method = a function defined inside a class.

Think of a character:
It has abilities like:

  • attack()
  • run()
  • speak()
  • castSpell()

Those are methods.

Example:

class Player {
  constructor(name, level) {
    this.name = name;
    this.level = level;
  }

  greet() {
    console.log(`Hi! I'm ${this.name}, level ${this.level} 💥`);
  }
}

Every player can talk at birth. How adorable 😌

💡 Pro Tip:

Methods are stored once in memory,
so they don’t get duplicated with every new object — very efficient.


💛 4) Inheritance: “Who are you son? I’m your ancestor class!”

Sometimes one class wants the features of another class.

Example:
Animal → Dog

  • Every dog is an animal
  • Animals can breathe
  • Dogs can breathe and bark

Example:

class Animal {
  breathe() {
    console.log("I’m breathing...");
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof woof! 🐶");
  }
}

const dog = new Dog();
dog.breathe();
dog.bark();

💡 Pro Tip:

Inheritance is a magical sword that kills duplicate code in big projects.


💛 5) super(): Time to Call Your Dad

A child class uses super() to access the parent class constructor.

Example:

class Character {
  constructor(name) {
    this.name = name;
  }
}

class Mage extends Character {
  constructor(name, mana) {
    super(name); // calling Character’s constructor
    this.mana = mana;
  }
}

super → just like a rich kid accessing their father’s bank account 😌


💛 6) Getter & Setter: The Data Guard Gates

Getter → intercepts while reading
Setter → intercepts while updating

This allows you to:

  • Format data
  • Validate data
  • Prevent errors

Example:

class Player {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name.toUpperCase();
  }

  set name(newName) {
    if (newName.length < 2) {
      throw new Error("Name is too short");
    }
    this._name = newName;
  }
}

const p = new Player("Cansu");
console.log(p.name); // CANSU
p.name = "Queen";
console.log(p.name); // QUEEN


💛 7) Static Methods: Functions That Don’t Need an Object

Some functions don’t belong to an instance,
they belong to the class itself.

Example:

class MathUtils {
  static square(x) {
    return x * x;
  }
}

console.log(MathUtils.square(8));

You can only call it on the class — not on objects.

What are they for?

  • Helper functions
  • Calculations
  • Formatting

💛 8) Private Fields (#): Secret Hidden Properties

Sometimes you don’t want anyone messing with your data.

With ES2022’s #privateFields, you can:

  • Make data inaccessible from outside
  • Keep things secure
  • Hide values like a sneaky genius 😏

Example:

class Bank {
  #balance = 1000;

  showBalance() {
    console.log(`Balance: ${this.#balance}₺`);
  }
}

const acc = new Bank();
acc.showBalance();

Trying to access it directly:
acc.#balance → ❌ error!


💛 9) A Realistic Mini Project: RPG Character System

Let’s build something more professional:

class Character {
  constructor(name, strength, hp) {
    this.name = name;
    this.strength = strength;
    this.hp = hp;
  }

  attack() {
    console.log(`${this.name} attacked with ${this.strength} strength 💥`);
  }

  status() {
    console.log(`${this.name} | Strength: ${this.strength} | HP: ${this.hp}`);
  }
}

class Mage extends Character {
  constructor(name, strength, hp, mana) {
    super(name, strength, hp);
    this.mana = mana;
  }

  castSpell() {
    console.log(`${this.name} cast a spell! ✨ Mana: ${this.mana}`);
  }
}

class Warrior extends Character {
  constructor(name, strength, hp, armor) {
    super(name, strength, hp);
    this.armor = armor;
  }

  defend() {
    console.log(`${this.name} used ${this.armor} armor to defend 🛡️`);
  }
}

const merlin = new Mage("Merlin", 50, 80, 120);
const thor = new Warrior("Thor", 80, 200, 50);

merlin.castSpell();
thor.defend();
merlin.attack();
thor.status();

This structure can already serve as the backbone of a mini game.


💛 10) Professional Tips (Useful in real-world development)

🔥 1. Keep classes small
One class = one responsibility.

🔥 2. Use private fields (#)
Especially for banking, authentication, or token data.

🔥 3. Use static methods for utility functions
Makes your code cleaner.

🔥 4. Don’t overuse inheritance
If needed, use composition instead.

🔥 5. Don’t use arrow functions inside classes
They mess up the this binding.


💛 Conclusion: You’re a JS Class Master Now!

Now you can:

  • Understand modern JavaScript classes
  • Use inheritance
  • Write getters & setters
  • Use private fields
  • Build professional examples

You’re officially an elite JavaScript wizard 🧙‍♀️✨

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir