iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Class Intro

A class packages data (fields) and behaviour (methods) into one reusable shape. Under the hood it's prototype-based, but the syntax matches what learners expect from Java, C#, Python.

Full anatomy

JS
class User {
  // Public fields — copied to each instance
  joined = new Date();

  // Private field — only this class can read/write
  #pwHash = "";

  // Constructor runs on `new`
  constructor(name, role = "member") {
    this.name = name;
    this.role = role;
  }

  // Instance method — lives on User.prototype, shared by all instances
  greet() { return `Hi, ${this.name}!`; }

  // Getter / setter
  get isAdmin() { return this.role === "admin"; }
  set role(r)   { this._role = r.toLowerCase(); }
  get role()    { return this._role; }

  // Static method — call on the class itself
  static fromJSON(text) {
    const { name, role } = JSON.parse(text);
    return new User(name, role);
  }
}

const u = new User("Ada", "Admin");
u.greet();             // "Hi, Ada!"
u.isAdmin;             // true
User.fromJSON('{"name":"Grace"}');

Where things live

KindStorage
MethodsOn User.prototype — shared by all instances
Public fieldsCopied to each instance at construction
Private fields (#name)Hidden — accessible only inside the class body
Static membersOn the class itself

Classes are strict

  • Class body is automatically strict mode.
  • Calling User(…) without new throws TypeError (helpful — constructor functions silently broke).
  • Class declarations are NOT hoisted — declare before use.
Tip: Use classes when you have many instances sharing behaviour. For one-off records or pure data, stick with object literals — they're lighter and play better with serialization.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Class Intro!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Mark a class field as private.

class Counter { count = 0; }

Test yourself

Q1. Private fields are prefixed with…
Q2. A class body runs in…
Q3. Static methods are called on…

Discussion

Loading…