Typescript-class类篇

在这里插入图片描述

TypeScript中的类与ES6一致
class Person {
	name: string;//声明类型 前面省略了关键字 public
	age: number;
	constructor(name: string, age: number) {//构造函数 实例化类的时候触发的方法
	        this.age = age;
	        this.name = name;
	}
	getName(name: string): void {
	        this.name = name;
	        console.log(this.name);
	 }
	 setName(name: string): void {
	        this.name = name;
	        console.log(this.name);
	 }
}
let person = new Person('Kissing', 20);
	
person.getName("spring");//spring
	
person.setName("faker");//faker
TypeScript中 类的继承
class Web extends Person {
	constructor(name: string, age: number) {
	     super(name, age);//super表示调用父类的方法
	 }
	 work(): void {
	     console.log(`${this.name}在运动`)
	 }
	 showAge(): void {
	     console.log(this.age);
	 }
}
	
let web = new Web('handsome', 40);
web.work();//handsome在运动
web.showAge();//40
TypeScript类中的修饰符
class Person {
	public name: string;//public公有属性可以当前类以及子类,和外面访问
	protected age: number;//保护属性,可以当前类以及子类访问,但不能被外部访问
	private sex: string;//私有属性,仅限当前类访问,子类和外部均不能访问
	constructor(name: string, age: number, sex: string) {
	    this.name = name;
	    this.age = age;
	    this.sex = sex;
	};
	getName() {
	     console.log(this.name);//Loki
	};
	getAge() {
	    console.log(this.age); 26
	};
	getSex() {
	  console.log(this.sex);//male
	}
};
let person = new Person('Loki', 26, "male");
person.getName();
person.getAge();
person.getSex();
alert(person.name);//Loki
alert(person.age);//报错 属性“age”受保护,只能在类“Person”及其子类中访问
alert(person.sex);//报错属性“sex”为私有属性,只能在类“Person”中访问

TypeScript中的类其中的静态属性和静态方法以及调用(一般用的不是很多)
class Season {
	static third: string = 'autumn';//使用关键字static
	first: string;
	public second: string;
	constructor(first: string, second: string) {
	    this.first = first;
	    this.second = second;
	};
	getFirst() {
	    console.log(this.first);
	};
	getSecond() {
	    console.log(this.second + "-" + Season.third);
	}
	static four() {
	    console.log('this is four');
	}
}
let season = new Season('spring', 'summer');
console.log(Season.third);//查看属性
Season.four();//调用方法

谢谢观看 !!! 如有不足,敬请指教

猜你喜欢

转载自blog.csdn.net/handsomezhanghui/article/details/107459796
今日推荐