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在类的外部无法被访问