Programming/JavaScript

상속(inheritance)

잇나우 2019. 12. 21. 19:13
반응형

객체(오리지널, 부모객체)를 그대로 물려받아서 새로운 객체를 만들 수 있다. 상속받은 객체가 부모객체의 어떠한 기능은 제거하거나 추가해서 자신의 맥락에 맞게 부모의 객체의 로직을 재활용하면서 추가하거나 제거하는 것이 상속의 기본적인 동작방법이다. 부모의 재산을 상속받듯이 오리지널 객체가 가진 기능을 상속받는 객체가 동일하게 가질수 있다.

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

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

> My name is apple

두 코드의 결과는 같다. person이라는 생성자를 만들었고 그 생성자 바깥쪽에서 person이라고 하는 객체에 prototype이라고 하는 (특수한)프로퍼티에 name이라고 하는 프로퍼티를 준것이다. prototype 안에는 어떠한 객체가 들어가있다. 객체.변수이름을 하여 객체안에 메소드나 값을 준것이다.

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('apple');
document.write(p1.introduce()+"<br />");

name이라고 하는 프로퍼티 값을 apple로 지정해준것이다. programmer 라고하는 생성자와 생성자 안에는 introduce라는 메소드가 정의되어 있지 않다. 이것은 person 이라고 하는 객체의 prototype으로 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";
}
 
function Designer(name){
    this.name = name;
}
Designer.prototype = new Person();
Designer.prototype.design = function(){
    return "beautiful";
} 
 
 
var p1 = new Programmer('apple');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");

var p2 = new Designer('banana');
document.write(p1.introduce()+"<br />");
document.write(p1.design()+"<br />");

programmer에만 coding이라고 하는기능을 가지고 있어야 한다면 person에는 coding이라는 기능이 없어야하고 programmer는 coding이란 기능이 있어야한다. programmer.prototype.coding 이라하고 메소드를 설정해주면 coding을 실행했을때 그 메소드가 실행된다. person이라고 하는 공통의 부모가 있고 programmer라고하는 객체와 designer라고하는 객체가 person이라고하는 객체를 상속받는 것이다. 부모 객체의 내용을 수정하면 그것을 상속받고 있는 객체들의 내용도 전부 바뀌어 버린다.

반응형

'Programming > JavaScript' 카테고리의 다른 글

표준 내장 객체의 확장  (0) 2019.12.23
Prototype  (0) 2019.12.22
this  (0) 2019.12.20
생성자와 new  (0) 2019.12.17
함수의 호출 apply  (0) 2019.12.16