欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TypeScript——类及修饰符

程序员文章站 2022-07-03 23:18:11
...

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

    需要注意的是,在类中如果不声明变量或函数的类型,默认是public

	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 {
		privata name: string
		constructor(theName: string) {
			this.name = theName
		}
	}
	new Animal("Cat").name // error  因为name属性是私有属性

protected

    protected修饰符与private修饰符的行为很相似,唯一不同的是protected成员在派生类中可以访问

	class Person {
		protected name: string
		constructor(name: string) {
			this.name = name
		}
	}
	class Employee extends Person {
		private department: string

		constructor(name: string, department: string) {
			super(name)
			this.department = department
		}

		public getElevatorPitch() {
			return `Hello, my name is ${this.name} and I work in ${this.department}`
		}	
	}

	let howard = new Employee("Howrad", "Sales")
	console.log(howward.getElevatorPitch())
	console.log(howard.name) //error 不能直接访问name属性,protected类型可以在派生类中访问返回

    并且如果构造函数被标记成protected类型,意味着这个类不能在类的外部被实例。但是可以通过继承被派生类实例

	class Person {
		protected name: string
		protected construcot(theName: string) {
			this.name = theName
		}
	}

	class Employee extends Person {
		private department: string

		constructor(name: string, department: string) {
			super(name)
			this.department = department
		}

		public getElevatorPitch() {
			return `Hello, my name is ${this.name} and I work in ${this.department}
		}
	}

	let howard = new Employee("Howard", "Sales")
	let join = new Person("John") // error Person的构造函数是受保护的,即不能被实例化

readonly 修饰符

    可以在类中通过readonly关键字将属性声明为只读,并且只读属性必须在声明时或构造函数初始化

	class Octopus {
		readonly name: string 
		readonly numberOfLegs: number = 8
		constructor (theName: string) {
			this.name = theName // 只读属性只能在构造函数中初始化
		}
	}
	let dad = new Octopus("Man with the 8 strong legs")
	dad.name = "Man with the 3-piece suit" // error 只读属性不能修改值

存取器

    在TypeScript中支持通过getters/setters来截取对对象成员的访问

	let passcode = "secret passcode"

	class Employee {
		private _fullName: string

		get fullName(): string {
			return this.fullName
		}

		set fullName(newName: string) {
			if (passcode && passcode === "secret passcode") {
				this._fullName = newName
			} else {
				console.log("Error: Unauthorized update of employee")
			}
		}
	}

	let employee = new Employee()
	employee.fullName = "Bob Smith"
	if (employee.fullName) {
		alert(employee.fullName)
	}

静态属性

    学过Java这类语言的对静态属性应该不会陌生,静态类型即绑定在类上,不需要通过实例化就可以访问的。

	class Student {
		static a: string = 'aaaa'
	}
	console.log(Student.a)

抽象类

    抽象类一般用于基类,即被派生类继承。

	abstract class Animal {
		abstract makeSound(): void
		move(): void {
			console.log('roaming the earch')
		}
	}

	class class Dog {
		constructor() {
			super()
		}
	}