30 Days Of JavaScript

Day 12: Classes

Lesson 2: Instance variables

When we execute a classes constructor we get an instance of that class. Our triangle example from the previous lesson has two instance variables, height and width.

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

We can directly access those instance properties, just like with a normal object.

1const tri = new Triangle(10, 10);

The reason this instance properties exist is thanks to some syntactic sugar in JavaScript. Because the constructor has a height and width passed in, and then in the constructor we have assigned those to this.height and this.width respectively, JavaScript has filled in the blanks for us.

The full definition is really this.

Which doesn't look as clean as the first version, so it's nice that JavaScript is handling that for us I think.

Just like an object you can change the instance properties of an object.


Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co