Javascript (1) Javascript类的实现及应用

    本篇简单介绍javascrpt类的相关内容,具体内容如代码所示,对有面向对象编程经验的同学提供一个简易的参考。

    

class SimpleData{
	constructor(year, month, day){
		this._year = year;
		this._month = month;
		this._day = day;
	}
	
	getDay(){
		return this._day;
	}
	
	getYear(){
		return this._year;
	}
}

//模拟私有变量
class PrivateData{
	constructor(year, month, day){
		let _year = year;
		let _month = month;
		let _day = day;
		
		this.addDays = function(nDays){
			_day += nDays;
		}
		
		this.getDay = function(){
			return _day;
		}
	}
}

//javascript继承
class Polygon{
	constructor(height, width){
		this.name = 'Polygon';
		this.height = height;
		this.width = width;
	}
	
	sayName(){
		console.log("Hi, I am a ", this.name + ".");
	}
	
	sayHistory(){
		console.log('"Polygon" is derived from the Greek polus (many)' + 'and gonia (angle)');
	}
}

class Square extends Polygon{
	constructor(length){
		super(length, length);  //super要写在前面
		this.name = 'Square';
	}
	
	get area(){
		return this.height * this.width;
	}
	
	set area(value){
		this.area = value;
	}
}

$(document).ready(function(){
	curData = new SimpleData(2018, 11, 02);
	priData = new PrivateData(2018, 11, 02);
	
	poly = new Polygon(10, 5);
	square = new Square(50, 50);
	
	console.log("This year is:" + curData.getYear());
	
	console.log("This year is:" + curData._year);
	
	priData.addDays(5);
	
	console.log("Today is:", priData.getDay());
	
	poly.sayName();
	
	square.sayName();
	
	poly.sayHistory();
	
	square.sayHistory();
})

猜你喜欢

转载自blog.csdn.net/BoRenLiang/article/details/83684092