Classes
Follow along with code examples here!
Intro
In the last lecture, we learned about encapsulation - bundling data and methods that act on that data into an object. We learned about using closures to create private variables.
const makeFriendsManager = (...initialFriends) => {
const friends = [...initialFriends];
return {
getFriends() {
return [...friends];
},
addFriend(newFriend) {
if (typeof newFriend !== 'string') return;
friends.push(newFriend);
}
}
}Factory Functions Waste Memory
The nice thing about encapsulation is that we can re-use makeFriendsManager to create multiple objects that look alike: each friends manager has getFriends and addFriends methods.
This kind of function is called a factory function and each object created from this factory function is called an instance.
The objects myFM and yourFM definitely have the same behavior. But do they share that behavior? That is, are the methods they each have referencing the same exact function?
Q: Are the methods myFM.addFriend() and yourFM.addFriend() referencing the same exact function?
No! They are not the same. Each time the factory function is invoked, a brand new object is made and the methods are recreated as well. This is a waste of memory.
Classes

A class defines a type of object and the properties/methods that those objects will share.
Q: Suppose we wanted to create a class to represent users. What would the default properties be? What methods would be shared by each instance?
The
Userclass would have a constructor function for making aUserinstance with properties likeusername,email, andpasswordThe
Userclass might have methods likechangeUsernameorsetPassword
Class Definition and new
newMany programming languages implement classes in some manner.
In JavaScript, it starts with the class keyword, an uppercase name, and curly braces. Like this:
With a class definition, we can create new instances of that class using the new keyword. An instance is an object that is derived from a class.
Note: Even though User is treated like a function (we invoke it), you must use the new keyword when making an instance (you'll get an error if you don't)
Instanceof
We can use the instanceof operator (kind of like the typeof operator) to see if an object is derived from the given class.
Setting Properties With A Constructor
Right now, the class definitions only allow us to create blank objects. But objects are only useful if they have properties.
There are two kinds of properties that instances of a class can have:
Properties with default values that all instances start with
Properties whose values are provided when the instance is made
Class constructor functions have some quirks to get used to:
constructoris a special method name. You must use this name. When you create a new instance of a class usingnew, JavaScript will look to see if the class has aconstructormethod and it will execute that method.The
constructorfunction can accept parameters whose values are provided when the instance is madeThe
thiskeyword, when used in aconstructor,references the new instance object being created.
Defining Instance Methods
Remember, encapsulation wants us to bundle data with methods that operate on that data.
Adding methods to a class definition looks like this:
When used in a method, the this keyword refers to the object invoking the method.
Next time, we'll look at making the password private.
Quiz!
Can you spot the mistake(s) with the code below?
Q: Answer
The following mistakes are made:
constis used instead ofclassto define theAnimalclassWe don't need the
=to create the classThe
ownersproperty with the default value doesn't needthisThe
constructorfunction should be written like this:constructor () {}without the:and=>We don't need a comma to separate the methods
makeSoundshould usethis.soundWhen creating an instance of
Animal, thenewkeyword should be used.
Challenge
Create a class called FoodItem. Every instance of FoodItem should have the following properties and methods
name— the name of the itemprice- the price of the item in US dollarsweight- the weight of the itemgetPricePerPound()- returns the price / pound of the item
For example, I should be able to use this FoodItem class like so
Now, create a second class called ShoppingCart. Every instance of ShoppingCart should have the following properties and methods:
items— an array that starts empty. It should holdFoodIteminstances.addItem(FoodItem)— takes in aFoodIteminstance and adds it to theitemsarray.getTotalPrice()- calculates the total price of allFoodItemsin theitemsarray
For example, I should be able to use this ShoppingCart class like so
Summary
A class defines a type of object with shared methods and properties
It has a constructor function for defining the default properties that every instance of that class (objects of that type) will have.
All instances of that class inherit the class' methods.
Classes are defined using the
classkeywordInstances of a class are created using the
newkeyword and the class constructor.When used in a constructor function,
thispoints to the newly created objectWhen used in a method,
thispoints to the object invoking the method
Last updated