남고생들의 소소한 개발 일지
[JS] 상속 본문
상속
프로그래밍에서의 상속이란 부모 기능을 자식 넘겨주는 것을 의미한다.
상속을 통해서 코드의 중복을 줄일 수 있고, 공통된 기능을 한 곳에서 작성함으로서 코드의 관리가 쉬워진다.
먼저 상속의 기본 사용법을 알아보자.
function Green(color) {
this.color = color;
}
Green.prototype.color=null;
Green.prototype.paint = function(){
return 'Color is ' + this.color;
}
function Apple(color) {
this.color = color;
}
Apple.prototype = new Green();
var gr = new Apple('green');
document.write(gr.paint()+"<br />");
6행을 보면 Green의 prototype에 paint라는 함수를 만들어 주었다. prototype에 대한 설명은 다음강좌에 나오니 일단은 객체의 원형이라고 알아두자. 다음 14행 에서는 Apple의 prototype에 Green의 객체를 담는것으로 Green의 기능을 상속받게 된다. 16행에서는 변수 gr에 Apple객체를 담아주고 마지막 17행에서 gr에 paint함수를 부름으로서 'Color is green'을 출력하게 된다.
이처럼 Apple는 Green을 상속받음으로써 Green에 있는 paint함수를 가지게 된 것이다.
하지만 단순히 기능을 받아오는것만으로 끝이 난다면 상속이 아니더라도 방법은 있을것이다.
하지만 상속을 사용하는 이유는 기능을 받아오는것뿐만이 아니라 기능의 추가도 가능하다.
function Green(color) {
this.color = color;
}
Green.prototype.color=null;
Green.prototype.paint = function(){
return 'Color is ' + this.color;
}
function Apple(color) {
this.color = color;
}
Apple.prototype = new Green();
Apple.prototype.eat = function() {
return 'Eating Apple';
}
var gr = new Apple('green');
document.write(gr.paint()+"<br />");
document.write(gr.eat()+"<br />");
15행에 eat이라는 함수를 추가해주고 마지막에 eat를 호출해서 실행시켰다.
이처럼 상속을 용하면 부모가 가지고 있지 않은 기능을 추가할 수 있다.
참고
'프로그래밍 > JavaScript' 카테고리의 다른 글
| [JS] 표준 내장 객체의 확장 (0) | 2019.11.01 |
|---|---|
| [JS] prototype (0) | 2019.10.31 |
| [js]전역객체, this (0) | 2019.10.29 |
| [JS] 생성자와 NEW (0) | 2019.10.28 |
| [JS] arguments (0) | 2019.10.25 |