Problem Statement
Are ES6 classes truly different from constructor functions?
Explanation
ES6 classes are syntactic sugar over JavaScript's existing prototype-based inheritance.
Under the hood, classes still use prototypes and constructor functions.
Classes provide cleaner and more familiar syntax for developers from other languages.
Key differences: Class methods are non-enumerable by default. Classes must be called with new. Classes have stricter mode automatically.
The class syntax is preferred in modern JavaScript for creating objects, but understanding prototypes is still essential.
Classes make code more readable but do not change how JavaScript inheritance works internally.
Code Solution
SolutionRead Only
// ES6 Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I am ${this.name}`);
}
static create(name, age) {
return new Person(name, age);
}
}
// Equivalent constructor function
function PersonFunc(name, age) {
this.name = name;
this.age = age;
}
PersonFunc.prototype.greet = function() {
console.log('Hi, I am ' + this.name);
};
PersonFunc.create = function(name, age) {
return new PersonFunc(name, age);
};
// Both work the same way
const john = new Person('John', 30);
const jane = new PersonFunc('Jane', 25);
john.greet(); // 'Hi, I am John'
jane.greet(); // 'Hi, I am Jane'
// Both use prototypes
console.log(john.__proto__ === Person.prototype); // true
console.log(jane.__proto__ === PersonFunc.prototype); // true
// Class is still a function
console.log(typeof Person); // 'function'
// Key differences:
// 1. Class methods are non-enumerable
for (let key in john) {
console.log(key); // Only 'name' and 'age', not 'greet'
}
for (let key in jane) {
console.log(key); // 'name', 'age', and 'greet'
}
// 2. Classes must use new
// const bob = Person('Bob', 35); // TypeError!
// 3. Classes are in strict mode
class Test {
method() {
console.log(this); // undefined if called without object
}
}