This content originally appeared on DEV Community and was authored by Doug Jones
I see a lot of question asked about javascript. As I One of the things I have been studying is function vs classes.
One of the things I learned is that anything that can be written as a function can be written as a class.
Below I have typed out an example.
We have a book function that gives us some attributes of a book object.
Function
function Book(title, author, ISBN, numCopies) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.numCopies = numCopies;
}
Book.prototype.getAvailabitly = function() {
if (this.numCopies == 0) {
return "Out Of Stock";
} else if (this.numCopies < 10) {
return "Low Stock";
}
return "In Stock";
}
Book.prototype.sell = function(numCopiesSold = 1) {
this.numCopies -= numCopiesSold;
}
Book.prototype.restock = function(numCopiesStocked = 5) {
this.numCopies += numCopiesStocked;
}
const Divergent = new Book("Divergent", "Veronica Roth", 9780007550142, 5);
console.log(Divergent.getAvailabitly());
HungerGames.restock(12);
console.log(Divergent.getAvailabitly());
HungerGames.sell(17);
console.log(Divergent.getAvailabitly());
Class
class Book {
constructor(title, author, ISBN, numCopies) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.numCopies = numCopies;
}
get availability() {
return this.getAvailability();
}
getAvailability() {
if (this.numCopies === 0) {
return "Out of stock";
} else if (this.numCopies < 10) {
return "Low stock";
}
return "In stock";
}
sell(numCopiesSold = 1) {
this.numCopies -= numCopiesSold;
}
restock(numCopiesStocked = 5) {
this.numCopies += numCopiesStocked;
}
}
const Divergent = new Book("Divergent", "Veronica Roth", 9780007550142, 5);
console.log(Divergent.getAvailabitly());
HungerGames.restock(12);
console.log(Divergent.getAvailabitly());
HungerGames.sell(17);
console.log(Divergent.getAvailabitly());
Both will give you the same results.
But one of the things that I like about using a class method is that we can encapsulate our code so we know what function belong to the class. It helps us better organize our code and follow the flow.
As I am learning classes are becoming more of the standard when you have to choose between the two.
Hopefully as I learn I can continue to help make this path easier for others.
I hope this helps and as always
Happy Coding 👨🏿💻👨🏻💻🧑🏾💻👩💻
This content originally appeared on DEV Community and was authored by Doug Jones

Doug Jones | Sciencx (2022-07-04T02:53:27+00:00) Functional Class. Retrieved from https://www.scien.cx/2022/07/04/functional-class/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.