TypeScript 面向对象(一)

110 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情

面向对象这个概念跟之前我们学 java 时的是一样的,这里只做简单演示,如果觉得不理解,可以查看我之前写的 Java 面向对象简介 ,是个系列文章

//使用class关键字定义一个类
class Person {
    //定义实例属性
    //ps:static name 这样会报错,因为类中有一个默认的name属性,所以不能用static修饰name,可以换个别的名字 
    name: string = '孙悟空';
    //readonly表示只读属性,无法修改
    //readonly name:string = '孙悟空';
    //定义静态属性
    static age: number = 18;
    //定义方法,如果以 static 修改也变成了静态方法
    sayHello(){
        console.log("Hello");
    }
}

console.log(Person.age);
const person = new Person();
console.log(person.name);
person.sayHello();

在这里插入图片描述

类型注解

TS 中的对象是结构化的,在使用对象前,就可以根据需求,提前设计好对象的结构(建立一种契约,约束对象结构)

let person: {
    name: string
    age: number
    sayHello: () => void
    saySomething: (sth: string) => void
    sum: (num1: number, num2: number) => number
}

person = {
    name: '孙悟空',
    age: 18,
    sayHello() {
        console.log("Hello");
    },
    saySomething(sth: string) {
        console.log(sth)
    },
    sum(num1: number, num2: number) {
        return num1 + num2
    }
}

构造函数和this

class Dog{
    name:string;
    age:number;
    //构造函数会在对象创建时执行
    constructor(name:string,age:number) {
        //this表示当前实例
        console.log(this);
        this.name = name;
        this.age = age;
    }

    bark(){
        console.log("汪汪汪");
    }
}

const dog = new Dog("小黑",2);
const dog2 = new Dog("小白",3);
console.log(dog);

在这里插入图片描述

存取器

class Person {
        firstName:string
        lastName:string
        constructor(firstName:string,lastName:string) {
            this.firstName = firstName
            this.lastName = lastName
        }

        get fullName(){
            return this.firstName+"-"+this.lastName
        }

        set fullName(fullName:string){
            let arr = fullName.split('-')
            this.firstName = arr[0]
            this.lastName = arr[1]
        }
    }
    const person:Person = new Person('Errol','King')
    console.log(person.fullName)
    person.fullName = 'Lily-Rose'
    console.log(person.fullName)

在这里插入图片描述

继承

(function () {
    //定义一个表示狗的类
    class Animal {
        name:string;
        age:number;

        constructor(name:string,age:number) {
            this.name = name;
            this.age = age;
        }

        sayHello(){
            console.log("动物在叫");
        }
    }

    //定义一个表示狗的类,使 Dog 继承 Animal
    //Animal是父类,Dog是子类
    //子类将拥有父类全部属性和方法
    class Dog extends Animal{
        //子类覆盖父类方法是方法重写
        sayHello(){
            console.log("汪汪汪");
        }
    }

    //定义一个表示猫的类
    class Cat extends Animal{
        sayHello(){
            console.log("喵喵喵");
        }
    }

    const dog = new Dog("旺财",2);
    console.log(dog);
    dog.sayHello();

    const cat = new Cat("喵喵喵",1);
    console.log(cat);
    cat.sayHello();
})();

在这里插入图片描述