Whether it’s a laptop, smartphone, or a piece of furniture. Everything that exists has a purpose and parts. And was thoroughly planned out in a document somewhere to ensure requirements and quality are met.
Items like this were probably made in a factory (mass-produced), or less likely by a single person in some workshop. Maybe a shoemaker measured a client’s feet to make a mold. And used the mold to make a pair of expensive custom men’s leather shoes.
The mold is the prototype for all shoes made using that mold. And a shoe has variables/attributes: data that describes it and can change. For example,
Laces
(true
orfalse
)Material
(leather, polyester, etc…)Gender
(men’s/women’s, unisex)
From shoes to electronic devices, the items we have described so far are called objects. And because programming exists to solve real-world problems, it only makes sense that a concept such as an object exists in JavaScript.
Classes are blueprints for objects
Much like the shoe mold which served as a blueprint for all future shoes made with that mold, a class serves as a blueprint for creating an object with defined attributes and behaviors. As I have been told: classes are object factories. Or as MDN likes to put it:
Classes are a template for creating objects. They encapsulate data with code to work on that data.
-Mozilla Developer Network (MDN)
Encapsulate
is another way of saying classes group together data (properties and methods) with functions to process the data. A property
is just another name for a variable
in a class, and a method
is just a function
that is encapsulated in a class
. As I documented here, I recently made a to-do app using vanilla (non-framework) JavaScript
Real-world example: to-do app
I mentioned in a previous post I made a to-do app using local storage. What I didn’t mention- but a reader may have noticed if they looked at the CodePen linked at the end of the article- is that I encapsulated all the variables and functions into an object literal as an expression. let todoApp = {…properties and methods…}
.
Do you remember earlier when I mentioned shoes and smart phone as real-world objects? This todoApp
object literal is a one-off object with defined variables and behaviors (methods). To go a bit deeper, the todoApp
inherits from the Object
data type.
But that’s not important right now, what is important is that you see the syntax and relationship between the properties and methods of an object. For example, in the todoApp
example below, the addTodo
function adds items to the todos
array.
Notice all methods and properties are prefixed with this
keyword. It represents the current instance of the class.
let todoApp = {
todos: [],
addTodos: function() {
this.todos.push([{id: Date.now(), todo: this.getTodoInput()}]);
//pushes an array of an object with a key/value pair of id, todo
},
setTodos: function() {
localStorage.setItem("todos", JSON.stringify(this.todos));
// set a key called “todos“ in local Storage. The value is the todos array as a JSON string
},
getTodos: function() {
return JSON.parse(localStorage.getItem("todos"));
// return the todos key from local storage, return it as its original structure. In this case, an array
},
getTodoInput: function() {
let inputText = document.querySelector("#todo").value;
return inputText;
},
};
Another type of class exists called a constructor class. This aligns with the factory analogy from earlier. Here’s an example of a teamMate
class that is used to create an object of type teamMate
.
console.clear(); // clear the console
class teamMate {
constructor(name, location, cohort) {
this.name = name;
this.location = location;
this.cohort = cohort
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I'm from ${this.location} My cohort is ${this.cohort}.`);
}
}
// Creating instances of the teamMate class
var teamMateDerek = new teamMate("Derek", "California", "a-6");
var teamMateMarco = new teamMate("Marco", "NYC", "a-1");
console.log({teamMateDerek}, {teamMateMarco}); //object destructuring. A great way to distinguish the objects in the console.
Nothing has changed except the capabilities of the class and the way the class is used. We now prefix (add before) the new
keyword to the class name. i.e teamMate("Derek", "California", "a-6")
. But we still pass arguments to the method because, at the end of the day, a method is just a function encapsulated in a class.
A key difference remains between a constructor and a regular class and object literal. Instead of a one-off object as we saw with todoApp
, a constructor class is meant to be used multiple times to create multiple instances. It also has a special constructor method where the properties of an object are initialized (assigned) values.
As we have seen before, accessing a method looks like this:
console.log( teamMateMarco.sayHello() ); // “Hello”, my name is Marc and I‘m from NYC My cohort is a-1.”
Do you see the advantage of using classes to create objects to encapsulate data? How is it better than using global variables and functions? What are the downsides of using classes and objects?
Like all my posts, I love hearing from you. Let me know your thoughts in the comments!
Are u making me wanna start Java?