javascript模擬類及類繼承

// 模擬Class
		function Rectangle(width, height){															
			this.height = height;			// 實例變量(public)
			this.getWidth = function(){ return width; } // 實例變量(private)
			this.setWidth = function(w){ width = w; }
			Rectangle.INSTANCE_COUNT++;
		}
		Rectangle.prototype.getSize = function(){ return { width:this.getWidth(), height:this.height } }	// 實例方法
		Rectangle.INSTANCE_COUNT = 0; 												// 類變量
		Rectangle.getInstanceCount = function(){ return Rectangle.INSTANCE_COUNT; } // 類方法

		var s = new Rectangle(15,15);
		s.setWidth(50);
		
		console.log(s, s.getSize(), Rectangle.getInstanceCount(), Rectangle.INSTANCE_COUNT);

// 繼承
		function PositionRectangle(width, height, x, y){
			Rectangle.call(this, width, height); // 爲this添加, width, height屬性
			this.x = x;
			this.y = y;
			this.getPosition = function(){ return { x: this.x, y: this.y } }
		}

		PositionRectangle.prototype = new Rectangle(); // 只繼承方法
		delete PositionRectangle.prototype.width;
		delete PositionRectangle.prototype.height;

		PositionRectangle.prototype.constructor = PositionRectangle; // 修正構造函數

		s = new PositionRectangle(15,15,10,10);
		console.log(s, s.getSize(), s.getPosition(), Rectangle.getInstanceCount(), Rectangle.INSTANCE_COUNT);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章