ts中类的定义、继承、修饰符

ts中类的定义

class Person{
	name: string // 属性 前面省略了public关键词
	age: number
		
	// 构造函数,实例化类的时候触发的方法
	constructor(name:string, age:number){
		this.name = name
		this.age = age
	}
	
	run():void{
		console.log(`${this.name}在运动`)
	}
}
var p = new Person('lucy', 22)
p.run()
class Person{
	name: string
	age: number
	constructor(name, age){
		this.name = name
		this.age = age
	}
	getName():string{
		return this.name
	}
	setName(name:string):void{
		this.name = name
	}
}
var p = new Person('lily', 18)
console.log(p.getName()) // lily
p.setName('lisa')
console.log(p.getName()) // lisa

ts中实现继承 extends super

class Person{
	name: string

	constructor(name:string){
		this.name = name
	}

	run(){
		console.log(`${this.name}在运动`)
	}
}

class Web extends Person{
	constructor(name:string){
		super(name); // 初始化父类的构造函数
	}
	
	work(){
		console.log(`${this.name}在工作`)
	}

	run(){
		console.log(`${this.name}在运动--子类run`)
	}
}

var w = new Web('lily')
w.run() // lily在运动--子类
w.work() // lily在工作

类里面的修饰符

ts里面定义属性的时候给我们提供了三种修饰符

  • public: 公有 在类里面、子类、类外部都可以访问
  • protected: 保护类型 在类里面 子类里面可以访问,在类外部没法访问
  • private: 私有 在类里面可以访问,在子类、类外部都没法访问

public:公有类型

属性如果不加修饰符 默认就是公有public

class Person{
	public name:string // 公有属性
	constructor(name:string){
		this.name = name
	}
	run () {
		console.log(`${this.name}在运动`)
	}
}
class Web extends Person{
	constructor(name:string){
		super(name)
	}
	work():void{
		console.log(`${this.name}在工作`)
	}
}
var w = new Web('lucy')
w.work() // lucy在工作

// 类外部访问公有属性
w.name // lucy

protected:保护类型

保护类型,在类和子类里面可以访问,类外部没法访问

class Person{
	protected name:string
	constructor(name:string){
		this.name = name
	}
	run(){
		console.log(`${this.name}在运动`)
	}
}

class Web extends Person{
	constructor(name:string){
		super(name)
	}
	work(){
		console.log(`${this.name}在工作`)
	}
}

var w = new Person('lisa')
w.run() // protected在类里面可以访问
w.name // 报错 protected 在类外部无法访问
w.work() // protected在子类中可以访问

private:私有类型

private只在类中可以访问,在子类和类的外部都不能访问

class Person{
	private name:string
	constructor(name:string){
		this.name = name
	}
	run(){
		console.log(`${this.name}在运动`)
	}
}
class Web extends Person{
	constructor(name:string){
		super(name)
	}
	work(){
		console.log(`${this.name}在努力工作`) // 报错 private在子类里面没法访问
	}
}
var w = new Web('lisa')
w.run() // private只在类的内部可以被访问
w.name // private在类的外部无法被访问
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值