Classes in JavaScript
Classes in JavaScript — ES6 syntax depth and prototype correlation
JavaScript lacked the traditional concept of "classes" as seen in languages like Java, C++, or Python for a long time. However, starting with ES6 (2015), the class syntax was introduced to create constructor-based objects in a simpler and more readable way. In this article, we'll explain how class is actually "syntactic sugar" over constructor functions, how the prototype chain works, and what to do (and not do) with classes.
class User { constructor(name) { this.name = name; }
greet() { console.log(Hello, ${this.name}); } }
const u = new User('Ani'); u.greet(); // Hello, Ani
What happens under the hood:
Usergreet() method is added to User.prototype
prototypeThis means the above class is essentially equivalent to the following constructor function at the engine level:
function User(name) { this.name = name; }
User.prototype.greet = function() { console.log(Hello, ${this.name}); };
Classes implement the same prototype-based inheritance, but with more readable syntax. When we create a method inside a class, it's automatically added to its prototype.
console.log(typeof User); // function console.log(User.prototype.greet); // function greet()
Object instanceof User: the new object inherits from User.prototype.
const u = new User('Karen'); console.log(u instanceof User); // true console.log(Object.getPrototypeOf(u) === User.prototype); // true
Classes are not hoisted (unlike functions). They must be defined before use.
const u = new User(); // ReferenceError class User {}
Class methods are non-enumerable, unlike object literal methods.
console.log(Object.keys(User.prototype)); // []
Classes always operate in strict mode.
class Test { constructor() { undeclaredVar = 5; // ReferenceError } }
Class methods are writable and configurable, but non-enumerable:
#methodName).
class Person { static sayHi() { console.log('Hi from class'); } }
Person.sayHi(); // OK new Person().sayHi(); // TypeError
For small or one-time objects, factory functions or object literals are often better choices.
In JavaScript, class is syntactic sugar built on top of the prototype system. While it doesn't bring a complete OOP system (despite looking similar), it provides a clean and readable API for implementing inheritance, method sharing, and static properties.
In the next part, we'll analyze inheritance using JavaScript classes, including extends, super(), and prototype chain extension.