상속은 기존의 생성자 함수나 객체를 기반으로 새로운 생성자 함수나 객체를 쉽게 만드는 것을 뜻한다. 기존의 객체를 기반으로 생성하기 때문에 새로 만들어지는 객체에는 기존 객체의 특성이 들어가 있다. 이것을 기존의 객체에서 유산(속성과 메서드)을 물려받는 것과 비슷하다고 해서 상속이라고 부른다.
Rectangle의 프로토타입을 Square에 상속한다.
// Rectangle의 넓이를 구하는 함수 functionRectangle(w, h){ letwidth=w; letheight=h;
this.getWidth=function(){ returnwidth; } this.getHeight=function(){ returnheight; } this.setWidth=function(value){ if(value<=0){ returnalert('음수를 넣을 수 없습니다.'); } returnwidth=value; } this.setHeight=function(value){ if(value<=0){ returnalert('음수를 넣을 수 없습니다.'); } returnheight=value; } } Rectangle.prototype.getArea=function(){ returnthis.getWidth()*this.getHeight(); }
// Square를 구하는 함수 // Rectangle 객체의 속성을 Square 객체에 추가 functionSquare(length){ this.copy=Rectangle; this.copy(length, length); }
// Ractanlg의 프로토타입을 Square 프로토타입에 복사 Square.prototype=Rectangle.prototype; Square.prototype.constructor=Square;
// 입출력 코드 letrectangle=newRectangle(Number(prompt('가로 입력')), Number(prompt('세로 입력'))); letsquare=newSquare(Number(prompt('제곱할 값 입력')));
// Rectangle로 부터 상속을 확인 alert(squareinstanceofRectangle);
Rectangle 객체의 속성을 Square 객체에 추가 하였고, Rectangle 객체의 프로토타입이 가진 속성과 메서드를 Square 객체의 프로토타입에 복사한 것이다. 최종적으로 상속이 되었는지 판단하는 방법은 instanceof키워드를 사용하면 된다. true가 출력이 되면 상속이 되었다는 뜻이다.