Docs/JavaScript/Classes & OOP

Classes

ES6 Classes adalah syntactic sugar untuk prototypal inheritance.

Fitur

  • constructor() — inisialisasi
  • Methods
  • extends — inheritance
  • super() — panggil parent constructor
  • static — static methods
  • Getters & Setters
script.js
Try It →
class Character {
  constructor(name, level = 1) {
    this.name = name;
    this.level = level;
    this.xp = 0;
  }
  gainXP(amount) {
    this.xp += amount;
    if (this.xp >= 100) { this.level++; this.xp -= 100; return true; }
    return false;
  }
  get info() { return this.name+" Lv."+this.level+" ("+this.xp+"/100 XP)"; }
  static create(name) { return new Character(name); }
}

class Warrior extends Character {
  constructor(name) { super(name, 1); this.weapon = "Sword"; }
  attack() { return "⚔️ "+this.name+" attacks!"; }
}

const hero = new Warrior("Arya");
let result = hero.info+"
";
result += hero.attack()+"
";
hero.gainXP(120);
result += hero.info+" (leveled up!)

";

const npc = Character.create("Guard");
result += "Static: "+npc.info;

document.getElementById('output').innerHTML = result;