Basics
Challenges
Classes
Debugging
Events
External Files
Flow Control
Forms
Functions
Html Elements
Installation
Interfaces
Keywords
Modules
Namespaces
Operators
Reference Files
String
Types
If you have a class (ex: Cat) which extends another class (abstract or not, ex: Animal),
and your derived class (Cat) has a constructor
,
then you must use the super
function keyword.
Each derived class (Cat) that contains a constructor function must call super()
which
will execute the constructor of the base class...even if the base class has an empty/no constructor.
Before we ever access a property on this in a constructor body, we have to call super()
.
This is an important rule that TypeScript will enforce.
Observe the code below.
super
is still required
in Cat because Cat has it's own Constructor.
class Animal
{
Name: string = "";
constructor(name: string)
{
this.Name = name;
}
}
class Cat extends Animal
{
ColorOfFur: string = "";
constructor(name: string, furColor: string)
{
super(name);
this.ColorOfFur = furColor;
}
Greeting = () : string => `${this.Name} says meow and his color is ${this.ColorOfFur}.`;
}
window.onload = function ()
{
let cat = new Cat("Spot", "Orange");
let superDemo = <HTMLElement>document.getElementById("super-demo");
superDemo.innerHTML = cat.Greeting();
};