八、TypeScript面向对象特性

版权声明:本文为博主原创文章,未经博主允许欢迎转载,请注明原文链接。一起交流,共同进步。 https://blog.csdn.net/newbie_907486852/article/details/83106610

                                               面向对象特性

1、类(class)

//属性可以使用public、private、protect修饰
class Person{ 
	constructor() {
        console.log("构造方法========");  
    }


    public name;
    public eat() {
        console.log("正在吃==========");
    }
}

var p1 = new Person();
p1.name = "pangzi";
p1.eat();

//类的继承
class student extends Person{
    code: string;
    //子类的构造方法必须调用父类构造方法
    constructor(code:string) {
        super();
        this.code = code;
    }
	
	doWoerk(){
	    //使用super关键字调用父类方法
		super.eat();
	}
}

var stu = new student("023145");

2、泛型(generic)

class Person{ 

    constructor() {
        console.log("构造方法========");  
    }

    public name;
    public eat() {
        console.log("正在吃==========");
    }
}

var p1 = new Person();
p1.name = "pangzi";
p1.eat();


class Student extends Person{
    code: string;
    //子类的构造方法必须调用父类构造方法
    constructor(code:string) {
        super();
        this.code = code;
    }
}

var stu = new Student("023145");


//泛型
var students: Array<Person> = [];
students[0]=new Student("023145"); 

3、接口(interface)

interface IPerson{
    name: string;
    age: number;
}

class Person{
    //使用接口来限制参数类型
    constructor(public config:IPerson) {
        
    }
}

var p1 = new Person({
    name: "pangzi",
    age:18
});
interface Animal{
    eat();
}

class Sheep implements Animal{
    eat() {
        console.log("实现接口的class必须实现这个方法");
    }
}

4、模块(module)

模块:类似java中的 导包。
一个文件就是一个模块,一个模块内部使用两个关键字export、import。
export:声明模块对外暴露什么
import:声明其他模块对这个模块提供什么

a.ts:

export var pro;

var pro1;

export  function func() {
    
}

export function func1() {
    
}

export class Clazz {
    
}

class Clazz1 {
    
}

b.ts:

import {pro} from "./a";

console.log(pro);

5、注解(annotation)

注解在类上、方法上、属性上,声明加载这个类(方法、属性)时需要做什么事情

在这里插入代码片

6、类型定义文件(*.d.ts)

在TypeScript中使用类型定义文件,帮助开发者在TypeScript中使用已有的JS工具包,比如JQuery。

猜你喜欢

转载自blog.csdn.net/newbie_907486852/article/details/83106610