The class method
class Dog {
constructor(name: string) {
this.name = name
}
name: string
run(){}}let dog = new Dog('wangwang')
Copy the code
- Constructor parameters and member attributes are annotated with type annotations
- If the constructor does not give
name
Attribute assignment, which is required when writing codename
Property to set an initial value, otherwise an error is reported - If you don’t want to set the initial value, you can change it to
name
Set to an optional propertyname? : string
inheritance
class Husky extends Dog {
constructor(name: string, color: string) {
super(name)
this.color = color
}
color: string
}
Copy the code
The modifier
public
All members of a class are public by default, meaning they are visible to everyone and can be explicitly declared
class Dog {
constructor(name: string) {
this.name = name
}
public name: string
run(){}}let dog = new Dog('wangwang')
Copy the code
private
Private members can only be called by the class itself, not by instances and subclasses of the class
class Dog {
constructor(name: string) {
this.name = name
}
public name: string
run() {}
private pri(){}}let dog = new Dog('wangwang')
dog.pri() / / an error
class Husky extends Dog {
constructor(name: string, color: string) {
super(name)
this.color = color
this.pri() / / an error
}
color: string
}
Copy the code
The constructor is private, so the class cannot be instantiated or inherited
class Dog {
constructor(name: string) {
this.name = name
}
public name: string
run() {}
private pri() {}
protect pro(){}}Copy the code
protected
Protected members can only be accessed in classes and subclasses, not in instances. Protected members cannot be instantiated, but can be inherited, as if declaring a base class
readonly
Read-only property that must be initialized and cannot be changed
class Dog {
constructor(name: string) {
this.name = name
}
readonly leg: number = 4
}
Copy the code
Constructor parameters can also be modified to make them instance properties
class Husky extends Dog {
constructor(name: string.public color: string) {
super(name)
this.color = color
}
}
Copy the code
static
Static modifiers, which can only be called by class name, not by instance, can be inherited,
class Dog {
constructor(name: string) {
this.name = name
}
static food: string = 'bones'
}
let dog = new Dog('wangwang')
Dog.food // bones
Husky.food // bones
dog.food // undefined
Copy the code