JavaScript Intermediate
What is ES6 class? How does it differ from function constructors?
ES6 Class Syntax
ES6 introduced the class keyword for a cleaner object-oriented syntax.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a sound.');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
const d = new Dog('Rex');
d.speak(); // 'Rex barks.'
Function Constructor (ES5)
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound.');
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(this.name + ' barks.');
};
Key Differences
| Feature | Class | Function Constructor |
|---|---|---|
| Syntax | Clean and concise | Verbose |
| Hoisting | Not hoisted (TDZ) | Hoisted (function declarations) |
| Strict mode | Enabled by default | Must add manually |
Requires new |
Enforced (TypeError without it) | Silently fails without new |
| Inheritance | extends + super |
Manual prototype setup |
| Static methods | static keyword |
Attach directly to the function |
Under the Hood
ES6 class is syntactic sugar — the underlying mechanism is still prototype-based inheritance.
typeof class Foo {} // 'function'
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
