1.2: Classes
With the implementation of ES6, JavaScript programmers can build applications with an object-oriented class-based manner. Meaning, classes can inherit functionality and objects are created from these classes. Here's an example:
TypeScript uses typical object-oriented patterns. Let's look at extending established classes to create new ones through inheritance:
This is one of the most basic inheritance features, getting properties and methods from base classes. So, redDragon
inherits the attack method from Monster
. This happens through the extends
keyword.
PUBLIC, PRIVATE, AND PROTECTED
TypeScript also follows another common Object Oriented feature; public, private, and protected keywords on class members/methods. These keywords work in the following:
Public - Public is the default setting. This sets the member to be freely available throughout a program.
Private - This means a member cannnot be accessed from outside its class.
Protected - Similar to private, however it can be accessed from its deriving classes
Let's take a look:
TestClass
has access to both of the private x
and protected y
. NewTest
has access to this.y
because it is a subclass of TestClass
. However, NewTest
will have the following error if the method multiply()
is ran:
Property 'x' is private and only accessible within class NewTest
Remember, private is ONLY available inside its class and will not appear in an instantiated subclass
STATIC PROPERTIES
TypeScript can also use static
members on a class. This means you can use the properties and methods, even if you don't instantiate it.
adapted from TypeScript Documentation,Understanding TypeScript by Maximilian Schwarzmüller, and Stack Overflow
NEXT SECTION
Last updated