记住jQuery吗? 是的,我也...... jQuery曾经用来把JavaScript世界带到风暴中的一件事是它的方法链接。 应用多个方法到一个元素的能力在图书馆的采用中是一个很大的因素。
那么,什么是多元化?
多样性是物体描绘不同形式的能力,取决于它是如何和在哪里使用的。
如何在TypeScript中实施方法链和多形行为?这种多形类型**来拯救。
使用这个类型的 polymorphic,你将返回这
作为一个类的方法的结果。这
将指当前类的实例。当另一个类扩展前一个类时,这
将指扩展的类的实例。这样,这
将根据它被称为的位置改变它的形式。这被称为 polymorphism。同样,因为我们返回了这
,我们可以称为其他方法,这些方法在类中或它是母类。
假设我们经营汽车租赁服务,所以在我们的汽车
类别中,我们有三个方法,即租赁
,记录
和退款
。
1class Car {
2 Rent(type:string) : this {
3 console.log(`${type} has been rented.`);
4 return this;
5 }
6
7 Record() : this {
8 console.log(`Car was rented at ${new Date().toLocaleString()}`);
9 return this;
10 }
11
12 Return(type:string) : this {
13 console.log(`${type} has been returned.`);
14 return this;
15 }
16}
我们的汽车
类的方法返回这
,这使得我们的方法变得多形化,随着我们继续前进,它就会变得更加清晰。
1class ElectricCar extends Car {
2 Charge() : this {
3 console.log(`Electric car has been charged.`);
4 return this;
5 }
6}
7
8class GasCar extends Car {
9 Refill() : this {
10 console.log(`Gas car has been refilled.`);
11 return this;
12 }
13}
就像汽车
类中的方法一样,电动汽车
和天然气汽车
中的两种方法都返回此
。
假设有人想租一辆电动汽车,所以我们创建了一个ElectricCar
类的实例,因为我们需要在给客户之前充电汽车,所以我们称之为充电
方法,它存在于我们的ElectricCar
类中。
我们的最终代码将是这样的:
1let electricCar = new ElectricCar();
2electricCar
3 .Rent("Electric car") // Electric car has been rented.
4 .Record() // logs current date and time
看看我们如何通过返回这
来美丽地 **链接方法。
现在,当客户返回租车时,我们可以将不同的方法链接到电动汽车
,记录它已经返回。
1electricCar.Return("Electric car") // Electric car has been returned.
2 .Record() // logs current date and time.
3 .Charge() // Electric car has been charged.
也就是说,即使从记录
方法返回的这
通常是汽车
类别的实例,而不包含充电
方法,我们仍然可以称之为充电
方法,因为这
关键字现在代表了电动汽车
类别的实例。
通过创建一个GasCar
类的实例,我们可以在我们的方法链中称呼Refill
,而不是Charge
在electricCar
示例中。
1let gasCar = new GasCar();
2gasCar
3 .Rent("Gas car") // Gas car has been rented.
4 .Record() // logs current date and time
5
6gasCar.Return("Gas car") // Gas car has been returned.
7 .Record() // logs current date and time.
8 .Refill() // Gas car has been refilled.
通过利用这种类型的Polymorphic,我们可以创建一个API,根据它的名称返回不同的结果。
最后,在本文中,我们从一个类扩展到一个类,这是最多TypeScript允许的。 如果你想从多个类扩展,请检查之前的(https://andsky.com/tech/tutorials/typescript-mixins)文章,它向你展示了如何做到这一点或一个(https://www.npmjs.com/package/mixin.ts)我创建的图书馆。
希望你喜欢这篇文章
😉