DEV Community

Doug Jones
Doug Jones

Posted on

Functional Class

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());
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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 👨🏿‍💻👨🏻‍💻🧑🏾‍💻👩‍💻

Top comments (1)

Collapse
 
sfleroy profile image
Leroy

That's because the first example is how people used to simulate using classes in JavaScript in the old days before actual classes existed. That even let you hide parts of the implementation like proper classes. Obviously real classes are a much cleaner setup and should be preferred in any new is code :)