ES6抽象、封装简单demo

       class Dog{	     //抽象Dog类
		constructor(hairColor,breed, age){
		this.hairColor =hairColor;
		this._breed =breed;
		this.age =age;
		this.runSpeed =null;
		Dog.instanceNumber++;
	}


	shout(){
		console.log('汪汪汪,我是有' +this.age + '岁的' + this.hairColor +this.breed);
	}


	run(){
		this.runSpeed ='10m/s';
		console.log('本狗的速度可是有' +this.runSpeed);
	}


	gnawBone(){
		console.log('拿到骨头了,最幸福的时刻');
		return this;
	}


	getInstanceNumber(){
		return Dog.instanceNumber;
	}


	get breed(){	//封装getter方法
		console.log('调用了get breed接口');
		return this._breed;
	}


	set breed(breed){	//封装setter方法,若果没有该setter方法,就没有办法改变_breed属性
		console.log('调用了set breed接口');
		this._breed =breed;
		return this;
		}
	}


	Dog.instanceNumber =0;	//抽象类的静态属性
	
	let dog1 =new Dog('白色','萨摩', 1);
	let dog2 =new Dog('灰色','二哈', 2);
	let dog3 =new Dog('咖啡色','泰迪', 1);
	
	dog1.shout();
	dog2.shout();
	dog3.shout();
	
	console.log(Dog.instanceNumber);
	
	dog1.breed ='萨摩变萨摩耶';
	dog1.shout();






	console.log:
		调用了get breed接口
		汪汪汪,我是有1岁的白色萨摩
		调用了get breed接口
		汪汪汪,我是有2岁的灰色二哈
		调用了get breed接口
		汪汪汪,我是有1岁的咖啡色泰迪
		3
		调用了set breed接口
		调用了get breed接
		汪汪汪,我是有1岁的白色萨摩变萨摩耶

你可能感兴趣的:(JS,ES6,ES7)