TypeScript Day 4 — Object orientation (Part 1)
Overview
Object orientation is a very important idea in programming, and it is simple: put briefly, every operation in a program has to be done through objects.
- For example:
- operating the browser means using the window object
- operating the web page means using the document object
- operating the console means using the console object
Everything goes through objects, and that is what object orientation means. So what on earth is an object? That takes us back to what a program is. The essence of a computer program is an abstraction of things in the real world, and the opposite of abstract is concrete — a photograph, say, is an abstraction of a particular person, a model car is an abstraction of a particular car, and so on. A program is an abstraction of things too: a thing that gets into a program becomes an object.
In a program every object is split into two parts, data and function. Take a person: name, sex, age, height, weight and so on are the data, while the ability to talk, walk, eat and sleep is the person's function. In an object, data is called a property and function is called a method. So in short, in a program everything is an object.
1. Classes and objects
To do object orientation and operate on objects you first need objects, so the next question is how to create one. To create an object you must first define a class; a class can be understood as the mould for an object, and in a program you can create objects of a given type from a class. For instance: you can create a person object from the Person class, a dog object from the Dog class, a car object from the Car class — different classes create different objects.
Defining a class:
class ClassName { propertyName: type; constructor(param: type){ // this in an instance method refers to the current instance object this.propertyName = param; } methodName(){ .... } }
Example:
class Person{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } sayHello(){ console.log(`Hi everyone, I'm ${this.name}`); } }
Using a class:
const p = new Person('Sun Wukong', 18); p.sayHello();
Tips
- Inside a class, this refers to the current object
class Dog { // properties are defined directly in the class name: string; age: number; // constructor // the constructor is called when the object is created constructor(name: string, age: number) { // this in an instance method refers to the current instance object // in the constructor the current object is the object being created // you can use this to add properties to the object being created console.log(this); this.name = name; this.age = age; } bark() { alert("sdsd"); } }// the one below can be read as shorthand for the class above, it is syntactic sugar class Dog { // properties are defined directly in the constructor constructor(public name: string, public age: number) { // empty here } bark() { alert("sdsd"); } }
2. Features of object orientation
2.1 Encapsulation (important!)
An object is essentially a container for properties and methods; its main job is to hold properties and methods, and that is what encapsulation means
By default an object's properties can be modified at will; to keep the data safe, TS lets you set permissions on properties
Read-only properties (readonly):
If you add a
readonlywhen declaring a property, the property becomes read-only and cannot be modifiedIn TS a property has three modifiers:
public(the default), accessible and modifiable in the current class, in subclasses and on instance objectsprotected, only accessible and modifiable in the current class and in subclassesprivate , only accessible and modifiable in the current class
Example:
public
class Person{ public name: string; // writing public or writing nothing is both public public age: number; constructor(name: string, age: number){ this.name = name; // can be modified in the class this.age = age; } sayHello(){ console.log(`Hi everyone, I'm ${this.name}`); } } class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; //can be modified in a subclass } } const p = new Person('Sun Wukong', 18); p.name = 'Pigsy';// can be modified through the object
protected
class Person{ protected name: string; protected age: number; constructor(name: string, age: number){ this.name = name; // can be modified this.age = age; } sayHello(){ console.log(`Hi everyone, I'm ${this.name}`); } } class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; //can be modified in a subclass } } const p = new Person('Sun Wukong', 18); p.name = 'Pigsy';// cannot be modified
private
For properties you don't want modified at will, you can make them
privateSetting a property straight to private means it can no longer be modified through the object
class Person{ private name: string; private age: number; constructor(name: string, age: number){ this.name = name; // can be modified this.age = age; } sayHello(){ console.log(`Hi everyone, I'm ${this.name}`); } } class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; //cannot be modified in a subclass } } const p = new Person('Sun Wukong', 18); p.name = 'Pigsy';// cannot be modified
Property accessors (important!)
We can define a pair of methods in a class for reading and setting a property; methods that read or set a property like this are called the property's accessors
The method that reads a property is called a
getter, the method that sets it is called asetterExample:
class Person{ private _name: string; private _age: number; constructor(name: string, age: number){ this._name = name; this._age = age; } get name(){ return this._name; } set name(name: string){ this._name = name; } get age(){ return this._age; } set age(age: number){ // you can put conditions in here to constrain the format or range of the data if(age >= 0) { this._age = age; } else { consle.log("Wrong number!"); } } } const p1 = new Person('Sun Wukong'); console.log(p1.name); // reads the name property through the getter p1.name = 'Pigsy'; // modifies the name property through the setter p1.age = -18; // this one errors, because we already set a condition
Static properties
Static properties (and methods) are also called class properties. Using a static property needs no instance — you go straight through the class
Static properties (and methods) start with
staticExample:
class Tools{ static PI = 3.1415926; static sum(num1: number, num2: number){ return num1 + num2 } } console.log(Tools.PI); console.log(Tools.sum(123, 456));
2.2 Inheritance
2.2.1 What is inheritance?
Inheritance is a concept from object-oriented software technology.
Through inheritance you can bring the properties and methods of another class (the parent class) into the current class (the subclass), so that the subclass object (the instance) has the parent's properties and methods, or the subclass inherits methods from the parent so that the subclass behaves the same way as the parent
The
extendskeyword can be used to create a subclass of an ordinary class or of a built-in object
Example:
class Animal{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } } class Dog extends Animal{ bark(){ console.log(`${this.name} is barking!`); } } const dog = new Dog('Wangcai', 4); dog.bark();Inheritance lets you extend a class without modifying it
2.2.2 Features of inheritance
1. Overriding (re-writing)
When inheritance happens, if a method in the subclass replaces the same-named method in the parent class, that is called overriding (re-writing) the method
Example:
class Animal{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } run(){ console.log(`the run method in the parent class!`); } } class Dog extends Animal{ bark(){ console.log(`${this.name} is barking!`); } run(){ console.log(`the run method in the subclass, it overrides the run method in the parent class!`); } } const dog = new Dog('Wangcai', 4); dog.bark();
2. The super keyword
Inside a class method,
supercan refer to the parent class of the current classIn a subclass you can use super to reference the parent class
Example:
class A{ name: string; constructor(name: string) { this.name = name; } sayHello() { console.log("Hello"); } } class A1 extends A { stAte: boolean; constructor(name: string, stAte: boolean) { //if the subclass writes its own constructor instead of the parent's, it must call the parent's constructor //to initialise the object super(name);// call the parent class's constructor this.stAte = stAte; } }
3. Abstract classes (abstract class)
An abstract class is a class made specifically to be inherited by other classes; it can only be inherited by other classes and cannot be used to create instances
abstract class Animal{ abstract run(): void; bark(){ console.log('the animal is making a sound~'); } } class Dog extends Animals{ bark(){ // super.bark(); console.log('Woof!'); } run(){ console.log('the dog is running~'); } } let an = new Animal(); // cannot be created let dog = new Dog(); //can be created dog.bark(); // outputs "Woof!" rather than "the animal is making a sound~"A method starting with abstract is called an abstract method; an abstract method has no body and can only be defined in an abstract class, and when you inherit an abstract class the abstract methods must be implemented
Important
This article was translated by Hermes Agent; the original text can be found at here. The translation is for reference only. Translation time: 2026-11-05
