JavaScript Patterns: ES6 Class vs Constructor Function

A tale of two JavaScript patterns and the bugs that catch you out 🐛 I've been revisiting the two main ways to create custom objects in JavaScript. Both achieve the same goal. Both have traps. Here's what I found: ES6 Class class Character { constructor(name) { this.name = name this.powers = [] } addPowers(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Methods live outside the constructor, inside the class body. They land on the prototype automatically so every instance shares one copy rather than each carrying its own. Constructor Function function Character(name) { this.name = name this.powers = [] this.addPowers = function(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Easy gotcha: write function addPowers() instead of this.addPowers = and the method becomes a private inner function completely invisible outside the constructor. Your code won't error on creation, it'll just silently fail when you try to call it. The class syntax is cleaner and harder to get wrong. But understanding constructor functions teaches you what's actually happening under the hood and makes legacy codebases far less scary. Worth noting: there is a third way Object.create() but I've not covered it here. It gives you very fine-grained control over the prototype chain, but it's significantly more verbose and rarely the first tool you'd reach for. Both patterns. Both worth knowing. Have you been caught out by either of these? Let me know below 👇 #JavaScript #WebDevelopment #CodingTips #OOP #LearnToCode #JSDevs #SoftwareEngineering

To view or add a comment, sign in

Explore content categories