Class
Classes are object blueprints
Each instance of a class has its own unique properties
One class => One / Many objects
Example: Basic Class
Classes are defined with the class
keyword, and instantiated with the new
keyword
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
introduce(){
return "Hello, I'm " + this.name;
}
}
var p = new Person("Hemant");
console.log(p.introduce());
Inheritance
Classes can inherit properties from other classes
Child classes inherit all method and properties
class Vehicle {
speed: number;
constructor(speed){
this.speed = speed;
}
}
class Car extends Vehicle {
drive() {
console.log("Going " + this.speed + " MPH!");
}
}
class Honda extends Car{
drive() {
super.drive();
console.log("Honda Car " + this.speed + " MPH!");
}
}
var h = new Honda(190);
h.drive();
Public / Private Modifiers
Class properties are public by default
Public properties can be accessed through
object[propName]
Private properties cannot be accessed externally
class Lock {
private passcode : number;
constructor(passcode : number){
this.passcode = passcode;
}
unlock(code : number){
if (code===this.passcode){
console.log("Unlocked!");
}
}
}
var lock = new Lock(7777);
console.log(lock.passcode); // compile-time error
lock.unlock(7777); // ok
Accessors (Getters/Setters)
Let you define special functions for accessing or setting a variable
Looks like a normal public variable from outside the class
class Hamster{
private _name: string;
get name () : string {
return this._name;
}
set name (name : string) {
this._name = name;
}
}
var c = new Hamster();
c.name = "Hemant"; // set as property
console.log(c.name); // ( called as property not as function )
Note: setters/getters are supposed to be used as property not as function
Static Properties
Static properties belong to the class itself, and not an instance
class Ruler{
static centimeterToInch : number = 12;
convertCentimeters(cm:number) {
return cm * Ruler.centimeterToInch;
}
}
var ruler = new Ruler();
console.log(ruler.convertCentimeters(3)); // 36
console.log(Ruler.centimeterToInch); // 12
Last updated
Was this helpful?