Classes
The class syntax for building objects with shared behavior — constructors, methods, inheritance, and what it really is under the hood.
A class is a template for creating objects that share the same shape and behavior. It's cleaner syntax over JavaScript's prototype system (which you met in the Objects lesson) — under the hood, class methods still live on the prototype.
class Dog {
constructor(name) {
this.name = name; // instance property
}
speak() { // shared method (on the prototype)
return `${this.name} says woof!`;
}
}
const rex = new Dog('Rex');
console.log(rex.speak()); // Rex says woof!new Dog('Rex') creates an instance: it runs the constructor, sets this.name, and returns the new object. Every instance shares the same speak method rather than each holding its own copy.
#Inheritance with extends
class Puppy extends Dog {
constructor(name) {
super(name); // call the parent constructor
}
speak() {
return `${this.name} says yip!`; // override
}
}
console.log(new Puppy('Bit').speak()); // Bit says yip!Forgetting `new`
You must call a class with new. Calling Dog('Rex') without new throws a TypeError. And inside methods, this refers to the instance — which is why arrow functions (that don't bind this) make poor methods.
Where does the `speak` method live for every Dog instance?
Key takeaways
- A class is a template; `new ClassName(...)` runs the constructor and returns an instance.
- Instance properties are set with `this.x =` in the constructor; methods are shared via the prototype.
- `extends` inherits from a parent; `super(...)` calls the parent constructor.
- Classes are syntactic sugar over JavaScript's prototype system.
- Always call a class with `new`, and use regular methods (not arrows) so `this` binds to the instance.
What does this print?
class Cat {
constructor(name) { this.name = name; }
greet() { return 'meow, ' + this.name; }
}
console.log(new Cat('Lu').greet());This subclass throws 'must call super constructor'. Why?
class Animal { constructor(name) { this.name = name; } }
class Dog extends Animal {
constructor(name) {
this.legs = 4;
}
}Complete the line that creates an instance of the Timer class.
const t = Timer(60);
Write a Rectangle class with a constructor taking width and height, and an area() method that returns their product. new Rectangle(3, 4).area() should be 12.
Try it live — edit the code and hit Run to see the output: