웹 개발

javascript 상속

노루아부지 2019. 8. 17. 00:10
function Rectangle(w, h) {
	var width = w;
	var height = h;

	this.getWidth = function() { return width; };
	this.getHeight = function() { return height; };
	this.setWidth = function(value) {
    	if(value < 0) {
			throw '길이는 음수일 수 없습니다.';
		}
		else {
			width = value;
		}	
	};

	this.setHeight = function(value) {
		if(value < 0) {
			throw '높이는 음수일 수 없습니다.';
		}
		else {
			height = value;
		}
	};
}

Rectangle.prototype.getArea = function() {
	return this.getWidth() * this.getHeight();
};

function Square(length) {
	this.base = Rectangle;
	this.base(length, length);
};

Square.prototype = Rectangle.prototype;

var rectangle = new Rectangle(5, 7);
var square = new Square(5);

rectangle.setWidth(7);

alert(rectangle.getArea() + ' : ' + square.getArea() + ' , ' + square instanceof Rectangle);

1. this.setWidth와 같이 함수명 앞에 this를 붙여주어야 rectangle.setWidth(7); 과 같이 외부에서 사용할 수 있다.

2. throw '길이는 음수일 수 없습니다.'; 와 같은 throw 명령어는 alert을 띄우는게 아닌, script에러를 출력한다.

3. 상속의 확인 : alert(square instanceof Rectangle); 처럼 instanceof 키워드를 사용 할 때 true를 출력하면 상속되었다고 판단.

728x90

'웹 개발' 카테고리의 다른 글

html accesskey (단축키 지정)  (0) 2019.08.17
IE 8이하 차단  (0) 2019.08.17
ECMAScript 5 객체 속성 추가  (0) 2019.08.17
ECMAScript 5 객체 생성  (0) 2019.08.17
html/css - table 구조에서 열(column)단위로 숨기기  (2) 2019.08.17
loading