Classes and objects
As a quick refresher, objects are a collection of properties and methods. We saw them in Chapter 3, JavaScript Multiple Values. The properties of an object should have sensible names. So for example, if we have a person
object, this object could have properties called age
and lastName
that contain values. Here is an example of an object:
let dog = { dogName: "JavaScript",
weight: 2.4,
color: "brown",
breed: "chihuahua"
};
Classes in JavaScript encapsulate data and functions that are part of that class. If you create a class, you can later create objects using that class using the following syntax:
class ClassName {
constructor(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
}
let obj = new ClassName("arg1", "arg2");
This code defines a class with ClassName
as a name, declares an obj
variable, and initializes this with a new...