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 进行传参;

猜你喜欢

转载自www.cnblogs.com/mufc/p/11227148.html