typescript-ES6中的类(九)

ES5中的继承

<script>
  //借用父构造函数继承属性
  //1.父构造函数
  function Father(uname,age) {
    //this指向父构造函数的对象实例
    this.uname = uname
    this.age = age
  }

  //2.子构造函数
  function Son(uname,age){
    //this指向子构造函数的对象实例
    Father.call(this,uname,age)
  }
  var son = new Son('大数据',12)
  console.log(son)

</script>

ES6中类的继承

  • ES6类的继承使用extends关键字
class Parent{
  name: string
  static Adress: string = '成都市'
  private uname: string = 'Tom'
  #flag: boolean = false
  constructor(name: string){
    this.name = name
  }
  getName () {
    return this.name
  }
  static getNames () {
    return this.name
  }
}
// tslint:disable-next-line: max-classes-per-file
class Child extends Parent {
  age: number
  constructor(name: string,age: number) {
    super(name)
    this.age = age
  }
}

const ch = new Child('李氏',18)
console.log(ch)// {uname: 'Tom',name: '李氏', age: 18}
console.log(Child.getNames())// Child
// 判断父类
console.log(Object.getPrototypeOf(ch) === Parent)// true
// 属性“uname”为私有属性,只能在类“Parent”中访问
// ch.uname

// 属性 "#flag" 在类 "Parent" 外部不可访问,因为它具有专用标识符
// ch.#flag

Object.getPrototypeOf

  • 通过子类对象实例判断父类类型
    Object.getPrototypeOf(对象实例)
    
console.log(Object.getPrototypeOf(ch) === Parent)// true

super

作为函数

super()
  • 只能存在子类的构造方法中,且位于子类构造器给参数赋值的前面
    	constructor (){
    		super()	
    	}
    
  • super()作为函数,代表父类的构造方法

作为对象

class Parent{
  type: string
  static getType: () => string
  constructor (){
    this.type = 'parent'
  }
  getName () {
    return this.type
  }
}
Parent.getType = () => {
  return 'is Parent'
}

// tslint:disable-next-line: max-classes-per-file
class Child extends Parent {
  constructor (){
    super()
    console.log('constructor: '+super.getName())
  }
  getParentName () {
    console.log('getParentName: '+super.getName())
  }
  // 属性“getType”在类型“Parent”上不存在  super指代的父类的原型对象也不是父类本身
  // getParentType (){
  //   console.log('getParentType:'+super.getType())
  // }
  static getParentType (){
    console.log('getParentType:'+super.getType())
  }
}

const ch = new Child() // 创建实例对象,构造器初始化,输出: constructor: parent
ch.getParentName() // getParentName: parent
Child.getParentType()// getParentType: is Parent

类的prototype属性和_proto_属性

详见此处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值