Episode 9 of 11
Constructors (under the hood)
Understand how classes work under the hood — ES6 classes are syntactic sugar over JavaScript constructor functions and the prototype chain.
Constructors (under the hood)
ES6 classes are syntactic sugar — they look clean, but under the hood JavaScript uses constructor functions and prototypes. Understanding this is key to mastering JavaScript OOP.
Constructor Functions (Pre-ES6)
function User(name, email) {
this.name = name;
this.email = email;
this.online = false;
}
var userOne = new User('Shaun', 'shaun@example.com');
var userTwo = new User('Mario', 'mario@example.com');
console.log(userOne.name); // 'Shaun'
console.log(userTwo.name); // 'Mario'
How new Works
new User('Shaun', 'shaun@example.com')
// Under the hood:
// 1. Creates a new empty object {}
// 2. Sets 'this' to point to the new object
// 3. Runs the function body (this.name = name, etc.)
// 4. Returns the new object automatically
ES6 Class vs Constructor Function
// ES6 Class
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
login() {
console.log(this.name + ' logged in');
}
}
// Equivalent Constructor Function
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.login = function() {
console.log(this.name + ' logged in');
};
They Are the Same
class Foo {}
console.log(typeof Foo); // 'function'
// Classes are functions!
// The class syntax is just a nicer way to write constructor functions + prototypes
Adding Methods the Old Way
// Adding methods inside the constructor (bad):
function User(name) {
this.name = name;
this.login = function() { // Each instance gets its OWN copy
console.log(this.name);
};
}
// Adding methods on the prototype (good):
User.prototype.login = function() { // Shared across all instances
console.log(this.name);
};
Methods inside the constructor are duplicated for every instance (wastes memory). Methods on the prototype are shared — exactly what ES6 classes do automatically.
Key Takeaways
- ES6 classes are syntactic sugar over constructor functions
newcreates an empty object, setsthis, runs the function, and returns the objecttypeof MyClassis'function'— classes ARE functions- Class methods go on the prototype (shared), not on each instance (duplicated)