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  }
6}

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

1const tri = new Triangle(10, 10);
2
3console.log(tri.width);
4console.log(tri.height);

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.

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