상속

상속(inheritance)

상속객체의 로직을 그대로 물려 받는 또 다른 객체를 만들 수 있는 기능을 의미

(객체는 연관된 로직들로 이루어진 작은 프로그램이라고 할 수 있음)

단순히 물려받는게 아니라 기존의 로직을 수정하고 변경해서 파생된 새로운 객체를 만들 수 있게 해줌

1. 상속의 사용법

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 
function Programmer(name){ //Programmer이라는 생성자 만듦
    this.name = name;      //이 생성자의 prototype과 Person의 객체연결
}
Programmer.prototype = new Person();
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />"); 
//Programmer객체도 메소드 introduce를 사용할 수 있게 됨
//My name is egoing

2. 기능의 추가

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";
} //Programmer는 Person의 기능을 가지고 있으면서
  //동시에 Person이 가지고 있지않은 기능인 메소드 coding을 가지게 됨
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />"); //My name is egoing
document.write(p1.coding()+"<br />"); //hello world

Last updated