📌
Javascript 생활코딩
  • 자바스크립트
  • 자바스크립트 기본
    • 숫자와 문자
    • 변수
    • 주석, 줄바꿈과 여백
    • 조건문 - 기본
    • 조건문 - 비교연산자
    • 조건문 - 논리연산자
    • 조건문 - boolean의 대체재
    • 반복문 - 기본 (while,for)
    • 반복문 - 제어(break, continue)
    • 반복문 - 중첩
    • 함수
    • 배열 - 기본
    • 배열 - 조작, 제거 및 정렬 메서드
    • 객체 - 기본
    • 객체 - 반복문
    • 모듈
    • UI와 API 그리고 문서보는 법
    • 정규표현식
  • 함수지향
    • 유효범위
    • 값으로서의 함수와 콜백
    • 클로저
    • arguments
    • 함수의 호출
  • 객체지향
    • 객체지향 프로그래밍
    • 생성자와 new
    • 전역객체
    • this
    • 상속
    • prototype
    • 표준 내장 객체의 확장
    • Object
    • 데이터 타입
    • 참조
  • 패턴
    • 재귀함수
Powered by GitBook
On this page

Was this helpful?

  1. 객체지향

상속

상속(inheritance)

객체는 연관된 로직들로 이루어진 작은 프로그램이라고 할 수 있습니다. 상속은 객체의 로직을 그대로 물려 받는 또 다른 객체를 만들 수 있는 기능을 의미합니다. 단순히 물려받는 것이라면 의미가 없을 것입니다. 기존의 로직을 수정하고 변경하여 파생된 새로운 객체를 만들 수 있게 해줍니다.

아래 코드는 이전 시간에 살펴본 코드입니다.

function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
//My name is egoing

위의 코드를 아래와 같이 바꿔봅시다.

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
//My name is egoing

결과는 같습니다. 하지만 상속을 위한 기본적인 준비를 마쳤습니다. 이제 상속을 해봅시다.

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 
function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person();
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");

Programmer이라는 생성자를 만들었습니다. 그리고 이 생성자의 prototype과 Person의 객체를 연결했더니 Programmer 객체도 메소드 introduce를 사용할 수 있게 되었습니다.

Programmer가 Person의 기능을 상속하고 있는 것입니다. 단순히 똑같은 기능을 갖게 되는 것이라면 상속의 의의는 사라질 것입니다. 부모의 기능을 계승 발전할 수 있는 것이 상속의 가치입니다.

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 
function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person();
Programmer.prototype.coding = function(){
    return "hello world";
}
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");
//My name is egoing
//hello world

Programmer는 Person의 기능을 가지고 있으면서 Person이 가지고 있지 않은 기능인 메소드 coding을 가지고 있습니다.

PreviousthisNextprototype

Last updated 4 years ago

Was this helpful?