Javascript (1) Javascript類的實現及應用
阿新 • • 發佈:2018-12-19
本篇簡單介紹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(); })