JavaScript Classes
Classes provide cleaner syntax for creating constructor/prototype relationships. A class constructor runs when an instance is created with new. Methods defined in the class body are placed on the prototype rather than copied as own properties onto every instance.
Classes also support extends, super, private fields using #, static members, getters, and setters.
Class and Prototype Relationship
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hello ${this.name}`;
}
}
const user = new User('Suriya');
console.log(user.greet());
console.log(User.prototype.greet === user.greet);💡 The greet method is defined on User.prototype. The instance resolves it through the prototype chain.
Key Takeaways
- Classes are syntax built around JavaScript's prototype model.
- Class methods normally live on the prototype.
newcreates an instance and establishes the prototype relationship.
Knowledge Check
Where is a normal method defined in a JavaScript class placed?