- 类中变量定义
class Circle {
public x: number
public y: number
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}
class Circle {
constructor(public x: number, public y: number) {
this.x = x
this.y = y
}
}
- 类中属性类型
class Circle {
public x: number
protected y: number
private z: number
constructor(x: number, y: number, z: number) {
this.x = x
this.y = y
this.z = z
}
}
let circle = new Circle(1, 2, 3)
console.log(circle.x)
console.log(circle.y)
console.log(circle.z)
class Circle {
constructor(public readonly x: number, public y: number) {
this.x = x
this.y = y
}
setX(x:number){
this.x = x
}
}
- 子类重写父类方法时,方法的类型要统一,因为可能在子类方法中调用父类的方法,调用的时候要保证参数一致。
class Animal {
constructor(public name: string, public age: number) {
this.name = name
this.age = age
}
eat():string {
console.log('动物吃')
return '动物吃'
}
}
class Cat extends Animal {
constructor(public name: string, public age: number) {
super(name, age)
}
eat(){
super.eat()
console.log('猫吃饭')
return '猫吃饭'
}
}
class Singleton {
private static instance: Singleton;
private constructor() {
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod(): void {
console.log("调用了单例类的方法");
}
}
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);
instance1.someMethod();
abstract class Person {
public name = "lisi"
public fun1() {
return this.name
}
public abstract age: number
public abstract fun2(): string
abstract static habitat:string = "地球"
}
abstract class Person {
public abstract fun1: () => string
public abstract fun2(): string
}
class Stu extends Person {
fun1 = () => '123'
fun2() {
return '123'
}
}
class Example {
add(a: number): number;
add(a: number, b: number): number;
add(a: number, b?: number): number {
if (b) {
return a + b;
} else {
return a;
}
}
}
const example = new Example();
console.log(example.add(1));
console.log(example.add(2, 3));