freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #40 of 61

classes · constructor · methods · getters

LambdaVSThe Mutator
Lambda saysThe constructor initializes each instance; methods define shared behavior.

constructor(args) { this.x = args } runs once per new, setting up instance state on this. Methods defined in the class body live on the prototype and are shared across instances (memory-efficient). Add getters/setters for computed properties right in the class.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleAdd a constructor that stores a name and a method that greets using it.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>class User{ constructor(name){ this.name=name; } greet(){ return 'hi '+this.name; } }
document.getElementById('o').textContent=new User('drew').greet();</script></body></html>
▶ Open the interactive comic issue
‹ Classes · The ES6 SyntaxClasses · Inheritance · Extends · Super ›