Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 27, 2022 10:30 am GMT

object oriented programming in Javascript (part 4)

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


Original Link: https://dev.to/hacker4world/object-oriented-programming-in-javascript-part-4-2noi

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To