Classes

Classes are reusable templates for objects.

They encapsulate data and behavior by defining the structure (properties) and capabilities (methods) of an object in a consistent way. To understand why classes are important and distinct from interface specifications, consider this simple program for working with two-dimensional points:

Loading TypeScript...

Notice that the distance function uses the variable point to retrieve point.x and point.y. This is error-prone and unnecessarily complex, especially if we start making multiple Point objects.

Instead, we can use the special this variable, which automatically references the object that called the function.

Loading TypeScript...

Notice that this is not a variable name that you can define or directly change the value of - it is a special variable whose value is dependent on how the function is called.

Using this allows us to create reusable functions that can be assigned to any object.

Loading TypeScript...

Notice the this variable has a type of any, because TypeScript doesn't know which type of object is actually going to end up calling the function. It also only works in the example above because the compiler option noImplicitThis was set to false.

You can add a type for this as the first parameter of a function - notice the distance function still takes zero parameters when called.

Loading TypeScript...

Consider the example below, where we add an inspect function to various levels of a nested object.

Loading TypeScript...

Classes are functions

In JS a class is really just a special function

Was this page helpful?