class is a cleaner spelling of prototypes
A class does two things you already understand:
- The
constructorruns when you callnew ClassName(...), withthisset to a brand-new object. - Every method you write in the class body is placed on one shared prototype object,
ClassName.prototype. Instances get methods through the prototype chain from lesson 3-1, not as copies.
What new does, step by step: create an empty object, link its prototype to ClassName.prototype, run the constructor with this bound to that object, and return the object.
class is the spelling you will actually read and write at work — error subclasses, component classes, ORM models. Interviews probe whether you know it is the same prototype machinery underneath, because the abstraction leaks: this still follows the call-site rules from Unit 2, and methods still live in exactly one shared place.
Code exercise · javascript
Run it. Two instances, but `greet` exists exactly once, on the shared prototype. The `===` check proves both objects reach the same function.
Why interviewers care
Before class (2015), the same machinery was written with constructor functions: function User(name) { this.name = name } plus User.prototype.greet = function () {...}. You will still see this in older codebases and interview questions, and it behaves identically.
The key line to say in an interview: "class is mostly syntax over prototypes. Methods live on the prototype and instances reach them through the prototype chain." Also remember from lesson 2-1: a method pulled off an instance still loses this like any other function.
Quiz
You create 1,000 instances of `User`. How many copies of the `greet` function exist?
Two class tools you will meet immediately: get and static
- A getter (
get fahrenheit() { ... }) is a method you read like a property, no parentheses. Use it for values computed from other fields — since it recomputes on every read, it can never go stale the way a stored copy could. - A static method lives on the class itself, not on instances:
Temperature.fromFahrenheit(60). Statics hold alternative constructors and helpers that belong to no single instance. You have already used one:Object.createis a static method onObject.
Code exercise · javascript
Run it. `boiling.fahrenheit` has no parentheses — the getter runs on read. `fromFahrenheit` is called on the class itself and builds an instance for you.
Code exercise · javascript
Your turn. Write a class `Rectangle` with a constructor taking `width` and `height`, an `area()` method, and an `isSquare()` method returning true when width equals height.