ES6 Class Methods and Prototypes
Methods written in ES6 class syntax are automatically added to the `prototype` of the class, ensuring shared access among instances.
Key concepts
ES6 Class Prototype
Methods in ES6 classes are automatically added to the prototype. This behavior optimizes memory usage by sharing methods across all instances.
Step by step
Key Insight:
- This behavior optimizes memory usage by sharing methods across all instances.
Examples
ES6 Class Methods on Prototype:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
console.log(Person.prototype.greet); // function greet() { ... }
const person = new Person('Alice', 25);
person.greet(); // Hello, my name is AliceStuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus