码迷,mamicode.com
首页 > 其他好文 > 详细

typeScrip(三) 类

时间:2019-07-22 18:08:29      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:public   console   esri   extends   cal   type   私有   两种   this   

  es5 中类的创建以及继承

               function Animal(obj) {
			this.name = obj.name
			this.type = obj.type
			this.log = function () {
				console.log(`这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		function dog(obj) {
			Animal.call(this, obj)
			this.sex = obj.sex
			this.dogSay = function (){
				this.log()
				console.log(`dog:这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		const daHuang = new dog({name: ‘大黄‘, type: ‘犬科‘, sex: ‘公狗‘})
		console.log(daHuang)
		daHuang.dogSay()    

   es6 中类的创建以及继承

               class animal {
			constructor(obj) {
				this.name = obj.name,
				this.type = obj.type
			}
			log() {
				console.log(`这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		class dog extends animal {
			constructor(obj1) {
				super(obj1)
				this.sex = obj1.sex
			}
			dogSay() {
				super.log()
				console.log(`dog: 这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		const daHuang = new dog({name: ‘大黄‘, type: ‘犬科‘, sex: ‘公狗‘})
		console.log(daHuang)
		daHuang.dogSay()

     在es6的 constructor 中不去调用 super 的话是不能进行  this 的使用的,这里用 super(obj1) 是为了给所要继承的父类 animal 进行传参;

 

 

  共有public

    在 typeScript 中,类的属性和方法默认都是共有的,即成员默认都是 public;

 

 

  私有 private

    当成员被标记成 private 的时候,它就不能在声明的类之前去访问了,也不能被继承;在 typeScript 中的写法

               class animal {
                       private name: string;
			constructor(obj) {
				this.name = obj.name,
				this.type = obj.type
			}
			log() {
				console.log(`这个动物的名字是${this.name},属于${this.type}`)
			}
		}    

     在 typeSript 中,当我们比较两种不同的类型的时候,并不在乎它是从哪里得到的,如果所有成员的类型都是兼容的,我们就可以认为它们的类型是兼容的;然而,如果我们比较带有 private 或者 protected 的成员的类型的时候,就不行了,因为它们的类型是不兼容的;

 

 

  protected

    protected 和 private 之间的不同在于,定义protected 的属性不能被继承,但是在子类的方法中是可以拿到父类的这个属性的值的;例如:

               class animal {
                       protected name: string;
			constructor(obj) {
				this.name = obj.name,
				this.type = obj.type
			}
			log() {
				console.log(`这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		class dog extends animal {
			constructor(obj1) {
				super(obj1)
				this.sex = obj1.sex
			}
			dogSay() {
				super.log()
				console.log(`dog: 这个动物的名字是${this.name},属于${this.type}`)
			}
		}
		const daHuang = new dog({name: ‘大黄‘, type: ‘犬科‘, sex: ‘公狗‘})
		console.log(daHuang)   // dog: 这个动物的名字是大黄,属于犬科
		console.log(dahuang.name)   // error  ......name is protected

 

typeScrip(三) 类

标签:public   console   esri   extends   cal   type   私有   两种   this   

原文地址:https://www.cnblogs.com/mufc/p/11227148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!