- Notifications
You must be signed in to change notification settings - Fork0
CatPerry/covid-19-javascript-class-prototyping-tutorial
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
To learn the basics of JavaScript Classes and the key native-JavaScript concepts of prototypes and inheritance, and let's build a modern example: CoronaVirus Class!
See theCoronaVirus Class on Github; and follow me onTwitter. Read this article onDev.to.
##Why learn how to write native JavaScript classes?Technical interviews.
No, seriously.Learning how to write native JavaScript classes and deepening your understanding of prototypes may save you some sweating during technical interviews. This is a common interview question, especially for those without a CS degree, i.e., bootcamp grads, and if you don't know how to build themsans Frameworks like React or Angular, you'll be quickly skipped over. Plus, classes are the basis for all the components you'll whip up in JS frameworks. So knowing what's happening under the hood will make you a better engineer.
##Read the Documentation about JS ClassesReadMDN docs, thisSitePoint Classes article, orW3Schools doc on JavaScript Classes for everything related to writing classes.
Disclaimer: You MAY notice a touch of opinionated text in the base CoronaVirus Class. It's just a means of venting, but I want others to add their own flair/venting. If you want to directly contribute to this CoronaVirus Class and its docs, just open an issue and let's get it PR'd.
Use this open source project to explore the native JavaScript functionalities that include Classes, inheritance, prototyping, hoisting, etc! This class is for all of us!
##About JavaScript Classes
As per the MDN JavaScript Classes documentation, Classes are just syntax sugar to declare a function. They are JavaScript's approach to Object Oriented Programming (OOP), and they create anobject template. The components for a class are its declaration,Constructor keyword,Super keyword, class properties, class methods (both public and private), and special class methods calledGetters andSetters.
####How Prototypes Factor InThese methods and properties are all then available via the class-object'sprototype, and behind the scenes, you'll reference these via dot notation (e.g.,coronaDay42.newMethodName). But instead ofcoronaDay42.newMethodName, JavaScript is actually writingcoronaDay42.prototype.newMethodName. Another very common example of a prototype isArray.prototype.map(). So when you callmyArray.map(), what's really being called behind the scenes by JS isArray.prototype.map(). The same can be said for other very common JS methods like.split(), .splice(), .reverse() etc. Read more aboutInheritance and the Prototype Chain.
####Subclasses and ExtendsAnd then there areSub classes orChild classes, in which you will extend theparent class to use it with a subclass.A subclass inherits the prototypes of the parent class.
##How to Declare a Class###Class Declarations (example from MDN docs)
classRectangle{constructor(height,width){this.height=height;this.width=width;}}
###Class Expression(ex. from MDN docs)
letRectangle=class{constructor(height,width){this.height=height;this.width=width;}};// this class can be named or unnamed (e.g. this can also be `let Rectangle = class RectangleFactory {}`)
For the CoronaVirus Class exercise we use a classdeclaration.
##Parts of a Class###ConstructorTheconstructor keyword initializes the object and sets the included initial properties.
For CoronaVirus Class, the properties arethis.people,this.virus, andthis.ppeNumber.
Themethods that can be accessed in this class are these:
###Getters
gettheVirus()getdeliverableSafetyItems()getppeNow()getteamwork()getfullStory()
These methods can be accessed on any instance of the CoronaVirus Class, as inconsole.log(coronaDay42.fullStory);
###Setters
setteamwork(isThereTeamwork)setsafetyItems(item)
Setters are used to define a value; thus they require a parameter/value to set. Then it can be modified like the last line of code below does.coronaDay42.teamwork = randomYesOrNo;
letrandomYesOrNo=Math.floor(Math.random()*2);constcoronaDay42=newCoronaVirus(randomPeopleNumber,1000,randomPpeNumber);coronaDay42.teamwork=randomYesOrNo;
###MethodsThe class methods/functionsmultiplies() andrandomCountry() can be used very similarly to the classgetters except that when they are invoked, you must use the trailing parens(). So,coronaDay42.ppeNow is a getter andthis.multiplies() is the function. For the subtle differences in behavior and performance between the two, check out this really helpfulQuora response on "difference between using a getter method or a regular function in JavaScript".
##Creating Class Instances (and Invoking them)At the bottom of the CoronaVirus Class, you'll see the following:
letrandomPeopleNumber=Math.floor(Math.random()*58494);letrandomPpeNumber=Math.floor(Math.random()*58492084);letrandomYesOrNo=Math.floor(Math.random()*2);constcoronaDay42=newCoronaVirus(randomPeopleNumber,1000,randomPpeNumber);coronaDay42.teamwork=randomYesOrNo;console.log(coronaDay42.fullStory);
Thisconst coronaDay42 = new CoronaVirus(randomPeopleNumber, 1000, randomPpeNumber); is how the Class instance is created, setting a variable to anew CoronaVirus(). Then we pass in theclass properties of:
this.people=people;this.virus=virus;this.ppeNumber=ppeNumber;
From there, you can access the getters/setters/methods of the Class and build from there!
That's it for this class, but wait there's more!
##Other JavaScript Class functions and syntaxThe current CoronaVirus class is pretty simple and doesn't have some other core JS class functionality, including the following:
Inheritancethrough Subclasses! e.g.classCovid19extendsCoronaVirus{}
- Private methods
- Static methods
- Field declarations (public and private)
Super()(refers to the parent class)- And more.
I hope this guide helps you understand and manipulate JavaScript classes a bit more.
These are crucial parts of core JavaScript functionality to understand. They're often skimmed over by junior engineers, until they're asked about them during technical interviews. So learn them now, and never be stumped again by this classic and fundamental JavaScript knowledge again.
Have you ever been asked to build a class during a JavaScript interview? If so, how hard was it? Or what was the craziest "Build a JS class" interview question you were ever asked? Leave a note in the comments.
About
Learn the basics of JavaScript Classes and prototying via the CoronaVirus Class
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
