by now you should be familiar with constructor functions and prototypes and you understand how they work, now it is time to learn about ES6 classes
ES6 classes
classes were added after the release of ES6 to javascript and it's a new way to write blueprints for objects including props and methods
Example
let's recreate the Customer bluepring but now we will use ES6 classes instead
class Customer {
constructor(name, email, password, settings, cart) {
this.name = name;
this.email = email;
this.password = password;
this.settings = settings;
this.cart = cart;
}
setSettings(newSettings) {
this.settings = newSettings;
}
orderFood(food) {
console.log(`ordering ${food}`);
}
}
const customer = new Customer("name", "email", "password", {}, [])
c.orderFood("Pizza"); // ordering pizza
Explanation
when we create a new instance of this class, the code inside the constructor method will run and in this case i'm adding the taken props to the this keyword to build the object.
then all the methods declared under the constructor will be automatically added to the prototype so we don't have to worry about memory loss or attaching them to the prototype
Truth about ES6 classes
in reality ES6 classes are just fancy syntax to declare constructor functions and under the hood will be converted to
regular constructor functions
Top comments (0)