As with any language, the Class serves as a prototype for JavaScript to create objects. It however, is not an actual object itself.
While JavaScript objects have been around for a while, there were some larger changes to the process with the 2015 revision.
To create a class now, we use the class
keyword, and it is important to use the constructor()
method.
The general form for a class, therefore, might look something like the following:
class ClassName {
constructor() { /* ... */ }
}
Notice that we use a naming style similar to what you would find in Java or C++ where the class name is capitalized.
Classes can be as simple, or complex as you want. Here is an example of a simple Student class.
class Student {
constructor(name, major, gradYear) {
this.name = name;
this.major = major;
this.gradYear = gradYear;
}
}
Notice how we assign the parameters passed into the constructor as object level variables that can be used elsewhere inside of the object that will be created.
To instantiate the object, we write it like we would in many OO languages.
let student1 = new Student(); // create a basic object
console.log(student1); // display the object
Of course, because we’re expecting values, we don’t get to see anything but undefined values.
If we want to push data, we can do something like:
let student2 = new Student('Luigi', 'Civil Engineering', 2032);
console.log(student2);
Object Properties
You’ll notice that JavaScript doesn’t have the concept of public and private properties/methods. That means anyone can read and write from an instantiated object. It’s even possible to add new properties, sometimes. So always be careful, and use best practices to avoid potential errors.
Overloading Constructors?
JavaScript doesn’t allow us to overload a constructor. So how do we handle creating objects with different numbers of parameters being passed to the constuctor?
Well, you can use the Nullish Coalescing to assign default values, like you see here.
constructor(name, major, gradYear) {
this.name = name;
this.major = major;
this.gradYear = gradYear ?? new Date().getFullYear() + 4;
}
Methods in a Class
You can create a method inside of a class, by creating a function inside of the class definition. However, you do not have to use the function keyword first.
class Student {
constructor(name, major, gradYear) {
this.name = name;
this.major = major;
this.gradYear = gradYear ?? new Date().getFullYear() + 4;
}
hasGraduated() {
return this.gradYear < new Date().getFullYear();
}
}
Classes in JavaScript was originally found on Access 2 Learn
One Comment
Comments are closed.