typeScrip 类

Posted mufengchun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typeScrip 类相关的知识,希望对你有一定的参考价值。

  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 类的主要内容,如果未能解决你的问题,请参考以下文章

如何通过单击片段内的线性布局从片段类开始新活动?下面是我的代码,但这不起作用

elasticsearch代码片段,及工具类SearchEsUtil.java

Springboot + mybatis + React+redux+React-router+antd+Typescript: React+Typescrip项目的搭建

Android 逆向类加载器 ClassLoader ( 类加载器源码简介 | BaseDexClassLoader | DexClassLoader | PathClassLoader )(代码片段

为啥片段类应该是公开的?

片段内部静态类和gradle问题