30 Days Of JavaScript

Day 12: Classes

Lesson 1: What are classes

Classes are a way to define a template of an object, then create an instance of that object when needed and know that it comes with all the extra functionality that we need.

Let's see what that means. Here is how you define a class.

1class Triangle {
2  constructor(height, width) {
3    this.height = height;
4    this.width = width;
5  }
6}

This defines a class called Triangle that is created with a constructor which takes a height and width inside the constructor, we set the classes internal height and width to what was passed in with the this.height and this.width. Here this refers to literally this instance of the class.

This will sound confusing, it is much clearer when we use it.

Here you can see we defined the class and then created an instance of the class with new Triangle(10, 10) and then logged it out.

The constructor is what is called when new Triangle(10, 10) is executed and the new object that is created is returned an saved in tri.

This might seem like a more complicated way of making an object, and you would be right, but let's see what else we can do.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co