4

TypeScript类、继承、多态

 2 years ago
source link: https://www.fly63.com/article/detial/11778
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

TypeScript类、继承、多态

更新日期: 2022-06-21阅读量: 9标签: TypeScript分享

扫一扫分享

对于传统的 JavaScript 程序我们会使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员使用这些语法就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从 ECMAScript 2015,也就是 ES6 开始, JavaScript 程序员将能够使用基于类的面向对象的方式。 使用 TypeScript,我们允许开发者现在就使用这些特性,并且编译后的 JavaScript 可以在所有主流浏览器和平台上运行,而不需要等到下个 JavaScript 版本。

// 类
(() => {
    class Person {
        // 声明属性
        name: string
        age: number
        gender: string
        // 构造方法
        constructor(name: string='jkc', age:number=18, gender:string='男') {
            this.name = name
            this.age = age
            this.gender = gender
        }
        // 一般方法
        sayHi(str: string){
            console.log(`你好,我叫${this.name},今年${this.age}岁,性别${this.gender}, 我想说:`, str)
        }
    }
    // 创建类的实例
    const person = new Person()
    // 调用实例的方法
    person.sayHi('我很帅')
})()

如果你使用过C#或Java,你会对这种语法非常熟悉。我们声明了一个Person类。这个类有3个属性、一个构造函数和一个sayHi方法。
我们使用new构造了Person类的一个实例。它会调用构造函数,创建一个Person类型的新对象,并执行构造函数初始化它。最后通过person对象调用其sayHi方法

在 TypeScript 里,我们可以使用常用的面向对象模式。 基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。

class Animal {
    name: string
    constructor (name: string) {
        this.name = name
    }
    run (distance: number=0) {
        console.log(`${this.name} run ${distance}m`)
    }
}

class Snake extends Animal {
    constructor (name: string) {
        // 调用父类型构造方法
        super(name)
    }
    // 重写父类的方法
    run (distance: number=5) {
        console.log('sliding...')
        super.run(distance)
    }
}

class Horse extends Animal {
    constructor (name: string) {
        // 调用父类型构造方法
        super(name)
    }
    // 重写父类型的方法
    run (distance: number=50) {
        console.log('dashing...')
        // 调用父类型的一般方法
        super.run(distance)
    }
    xxx () {
        console.log('xxx()')
    }
}

const snake = new Snake('sn')   
snake.run()
const horse = new Horse('ho')
horse.run()

我们定义了一个超类Animal,两个派生类Snake和Horse,并且创建了2个实例对象snake和horse。
通过snake.run(),我们可以看到Snake中有run方法,那么就进行调用,最后结果如下

sliding... sn
run 5m

通过horse.run(),我们可以看到Horse中有run方法,那么进行调用,最后结果如下:

dashing... 
ho run 50m

定义:不同类型的对象针对相同的方法,产生了不同的的行为
接着上面的代码

// 父类型引用指向子类型的实例 ==> 多态
const tom: Animal = new Horse('ho22')
tom.run()
/* 如果子类型没有扩展的方法, 可以让子类型引用指向父类型的实例 */
const tom3: Snake = new Animal('tom3')
tom3.run()
/* 如果子类型有扩展的方法, 不能让子类型引用指向父类型的实例 */
const tom2: Horse = new Animal('tom2')
tom2.run()

这个例子演示了如何在子类里可以重写父类的方法。Snake类和 Horse 类都创建了 run 方法,它们重写了从 Animal 继承来的 run 方法,使得 run 方法根据不同的类而具有不同的功能。注意,即使 tom 被声明为 Animal 类型,但因为它的值是 Horse,调用 tom.run(34)时,它会调用 Horse 里重写的方法。
62b2753e14477.jpg

公共,私有与受保护的修饰符

默认为public

在上面的例子里,我们可以自由的访问程序里定义的成员。 如果你对其它语言中的类比较了解,就会注意到我们在之前的代码里并没有使用 public来做修饰;例如,C#要求必须明确地使用 public指定成员是可见的。 在TypeScript里,成员都默认为 public。

你也可以明确的将一个成员标记成 public。 我们可以用下面的方式来重写上面的 Animal类:

class Animal {
    public name: string;
    public constructor(theName: string) { this.name = theName; }
    public move(distanceInMeters: number) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

理解private

当成员被标记成 private时,它就不能在声明它的类的外部访问。比如:

class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

new Animal("Cat").name; // 错误: 'name' 是私有的.

理解 protected

protected 修饰符与 private 修饰符的行为很相似,但有一点不同,protected成员在派生类中仍然可以访问。例如

class Animal {
    public name: string

    public constructor (name: string) {
        this.name = name
    }

    public run (distance: number=0) {
        console.log(`${this.name} run ${distance}m`)
    }
}

class Person extends Animal {
    private age: number = 18
    protected sex: string = '男'

    run (distance: number=5) {
        console.log('Person jumping...')
        super.run(distance)
    }
}

class Student extends Person {
    run (distance: number=6) {
        console.log('Student jumping...')

        console.log(this.sex) // 子类能看到父类中受保护的成员
        // console.log(this.age) //  子类看不到父类中私有的成员

        super.run(distance)
    }
}

console.log(new Person('abc').name) // 公开的可见
// console.log(new Person('abc').sex) // 受保护的不可见
// console.log(new Person('abc').age) //  私有的不可见

readonly修饰符

你可以使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

class Person {
    readonly name: string = 'abc'
    constructor(name: string) {
        this.name = name
    }
}

let john = new Person('John')
// john.name = 'peter' // error

在上面的例子中,我们必须在 Person 类里定义一个只读成员 name 和一个参数为 name 的构造函数,并且立刻将 name 的值赋给 this.name,这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 Person 类的修改版,使用了参数属性

class Person2 {
  constructor(readonly name: string) {
  }
}

const p = new Person2('jack')
console.log(p.name)

注意看我们是如何舍弃参数 name,仅在构造函数里使用readonly name: string 参数来创建和初始化 name 成员。 我们把声明和赋值合并至一处。

参数属性通过给构造函数参数前面添加一个访问限定符来声明。使用 private 限定一个参数属性会声明并初始化一个私有成员;对于 public 和 protected 来说也是一样。

TypeScript 支持通过 getters/setters 来截取对对象成员的访问。 它能帮助你有效的控制对对象成员的访问。

下面来看如何把一个简单的类改写成使用 get 和 set。 首先,我们从一个没有使用存取器的例子开始。

class P{
    firstName: string = 'A'
    lastName: string = 'B'
    get fullName() {
        return this.firstName + '_' + this.lastName
    }
    set fullName(value) {
        const names = value.split('_')
        this.firstName = names[0]
        this.lastName = names[1]
    }
}

const p = new P()
console.log(p.fullName)

p.firstName = 'C'
p.lastName = 'D'
console.log(p.fullName)

p.fullName = 'E_F'
console.log(p.firstName, p.lastName)

静态成员:在类中通过static修饰的属性或方法,也就是静态成员或静态方法,静态成员在使用时是通过类名.的这种语法来调用

class People{
    static name1: string = 'jkc'
    // 构造函数是不能通过static修饰的
    constructor() {
    }
    static sayHi() {
        console.log("hello")
    }
}


People.name1 = 'jkc2'
console.log(People.name1)
People.sayHi()

抽象类:包含抽象方法(抽象方法一般没有任何具体的内容的实现),也可以包含实例方法,抽象类是不能被实例化,为了让子类进行实例化及实现内部的抽象方法。

abstract class P1 {
    // 抽象方法不能有具体的实现代码
    abstract eat()
    sayHi() {
        console.log('hello')
    }
}

class P2 extends P1 {
    eat() {
        // 重新实现抽象类中的方法,此时这个方式是P2的实例方法
        console.log("吃东西")
    }
}

const p2 = new P2()
p2.eat()
本文作者: Silent丿丶黑羽本文链接: https://www.cnblogs.com/jiakecong/archive/2022/06/20/16392796.html

链接: https://www.fly63.com/article/detial/11778


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK