typescript之类、接口、定义

TS引入了类的概念,可以看做是一个语法糖。通过class关键字,可以定义类

定义一个类

1
2
3
4
5
6
7
8
9
10
11
12
class Student {
constructor(x, y) {
this.x = x;
this.y = y;
}

toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

let s = new Student('wang','li')
  1. 类和模块内部默认采用严格模式
  2. constructor方法是类的默认方法,通过new生成对象实例时,自动调用该方法。一个类必须有constuctor 方法,如果没有显式定义,一个空的constuctor方法会被默认添加。
  3. 必须使用new命令来调用class
  4. 类不存在变量提升,只有先声明类,才能使用类。
  5. 类的方法内部如果含有this,它默认指向类的实例。但是如果我们单独将其方法提取出来,this值可能会指向当前运行的环境。这个时候可以用箭头函数(this值指向初始化的函数)

public、private、protected和readonly

publicprivateprotectedreadonly都是类的成员(属性)修饰符

  1. public

    在TS里,成员都默认为`public`。被`public`修饰的属性,我们在类的内外都可以自由访问到这些被定义的属性。
    
1
2
3
4
5
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name;//Cat
  1. private

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

    1
    2
    3
    4
    5
    class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
    }
    new Animal("Cat").name;//Error!: Property 'name' is private and only access
  2. protected

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Person {
    private name: string; //如果这儿是protected就可以
    constructor(name: string) { this.name = name; }
    }

    class Employee extends Person {
    constructor(name: string) { super(name)}
    public sayName() {
    return this.name;//ERROR!: Property 'name' is private and only accessible within class 'Person'.
    }
    }

    let xiaoming = new Employee("xiaoming");
    console.log(xiaoming.sayName());
  1. readonly修饰符

    readonly 关键字与 publicprivateprotected 不一样,它修饰的不是成员的访问权限,而是成员的再赋值权限。

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

接口

在面向对象的语言中,术语 interface 经常被用来定义一个不包含数据和逻辑代码但是用函数签名定义了行为的抽象类型。

但是对于TS来说,接口更重要的意义是对值所具有的 *结构* 进行类型检查。  接口根据属性划分,可以划分成三类,一种是**必选属性**,另一种是**可选属性**,还有一种就是**只读属性**。
1
2
3
4
5
6
7
8
9
10
11
interface AnimalVaule{
name?:string;
eat:string;
lifestyle?:string;
}
function Animal(animal:AnimalVaule){
this.name=animal.name;
this.eat=animal.eat;
this.lifestyle=animal.lifestyle;
}
let cat=new Animal({eat:"食肉动物",lifestyle:"昼伏夜出"});

可选属性 名字定义的后面加一个?符号

可选属性的好处: 可以对可能存在的属性进行预定义;可以捕获引用了不存在的属性时的错误。

只读属性 你可以在属性名前用readonly来指定只读属性:

做为变量使用的话用const, 做为属性则使用readonly

接口不仅仅能描述对象的属性,还能描述**函数类型**,**可索引类型**和**类类型**。(blur)

继承

TS允许我们通过extends关键字来 创建子类(实现继承)。 下面这个例子,Dog 类继承自 Animal 类,在Dog 类中我们可以访问父类 Animal 的属性和方法

1
2
3
4
5
6
7
8
9
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
}
class Dog extends Animal {
breed: string;
}

new Dog("mydog").name;//mydog

注意:包含构造函数的派生类必须调用super(),它会执行基类的构造方法。

感谢你的打赏哦!