Classes and Prototypes
Object-oriented programming in JavaScript
Introduction
In this lesson, you'll learn about classes and prototypes in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with object-oriented programming in javascript.
JavaScript has its own approach to object-oriented programming in javascript, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
class Shape {
constructor(color) {
this.color = color;
}
describe() {
return `A ${this.color} shape`;
}
static default() {
return new Shape("red");
}
static info() {
return "I am a shape";
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle("blue", 5);
console.log(c.describe());Comparing to Python
Here's how you might have written similar code in Python:
class Shape:
def __init__(self, color):
self.color = color
def describe(self):
return f"A {self.color} shape"
@classmethod
def default(cls):
return cls("red")
@staticmethod
def info():
return "I am a shape"
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
c = Circle("blue", 5)
print(c.describe())You may be used to different syntax or behavior.
@classmethod → static method that returns new instance
You may be used to different syntax or behavior.
@staticmethod → static method (no cls/self)
You may be used to different syntax or behavior.
JS has only static — no @classmethod distinction
You may be used to different syntax or behavior.
super() in JS requires no arguments in the class body
Step-by-Step Breakdown
1. Constructor
JS uses constructor() instead of __init__(). this replaces self.
def __init__(self, x):
self.x = xconstructor(x) {
this.x = x;
}2. Static Methods
JS static methods cover both Python @staticmethod and @classmethod.
@classmethod
def default(cls): return cls("red")
@staticmethod
def info(): return "..."static default() { return new Shape("red"); }
static info() { return "..."; }3. Inheritance
extends and super work like Python's class Child(Parent) and super().__init__().
class Circle(Shape):
def __init__(self, c, r):
super().__init__(c)class Circle extends Shape {
constructor(c, r) {
super(c);
}
}Common Mistakes
When coming from Python, developers often make these mistakes:
- @classmethod → static method that returns new instance
- @staticmethod → static method (no cls/self)
- JS has only static — no @classmethod distinction
Key Takeaways
- constructor + this ≈ __init__ + self
- extends / super ≈ (Parent) / super().__init__
- One static keyword covers both @staticmethod and @classmethod