ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 객체 지향 프로그래밍(5) - 상속의 방법(ES5 / ES6)
    JavaScript 2020. 6. 21. 23:37

    상속의 방법으로는 크게 2가지가 있다.

    ES5에서의 pseudoclassical 방법과, ES6의 class 키워드를 이용한 방법이다.

     

    1. ES5(Pseudoclassical) 문법

    function Person(name){//부모 객체(생성자 함수) Person의 속성으로 name을 정의.
      this.name = name;
    }
    Person.prototype.introduce = function(){//Person의 prototype객체에 메서드 introduce를 정의.
      return 'My name is ' + this.name;
    }
    
    function Singer(name, style){
    Person.call(this, name);//자식 객체(생성자 함수) Singer에서 부모 객체 Person의 속성을 받아옴.
       this.style = style;//Singer 자체의 속성인 style을 만들어 줌.
    }
    
    Singer.prototype = Object.create(Person.prototype);
    // Singer의 prototpye에, Person의 prototype 객체의 속성과 메서드를 갖는 새로운 객체를 만들어서 할당.
    // 이때 Singer.prototype의 constructor는 Person을 가리키게 된다
    Singer.prototype.constructor = Singer;
    // Singer의 prototype객체 안의 constructor 프로퍼티가 다시 Singer를 가리키게 함.
    Singer.prototype.sing = function(){//Singer의 prototype객체에 sing이라는 메서드를 정의
      return 'shubidubap~~~';
    }
    
    let musician = new Singer('jinchuu', 'R&B');
    console.log(musician.name) // jinchuu
    console.log(musician.style) // R&B
    musician.introduce() // My name is jinchuu
    musician.sing() // shubidubap~~~

     

    2. ES6 문법

    class Person{
      constructor(name){ //new Person()이 실행될 때 constructor함수를 실행하게 된다
        this.name = name;
      }
        
      introduce(){ //함수를 정의할 때 function 키워드를 쓰지 않음
        return 'My name is ' + this.name;
      }
    }
    
    class Singer extends Person{ //extends 키워드를 통해 Person이 가지고 있는 속성들이 Singer에 상속된다
      constructor(name, style){
        super(name); // super 키워드를 통해 부모 class의 생성자를 호출
        this.style = style;
      }
    
    // 부모 class인 Person의 introduce 메서드에서 기능이 추가된 Singer만의 introduce 메서드를 만들 수 있다
    // super 키워드를 통해 부모 class인 Person의 introduce를 호출할 수 있다
      introduce(){ 
        return super.introduce() + `, I'm ${this.style} vocal!` 
      }
      
      sing(){ // Singer 생성자에 sing 메서드를 만든다
              return 'shubidubap~~~';
      }
    }
    
    let musician = new Singer('jinchuu', 'R&B');
    console.log(musician.name) // jinchuu
    console.log(musician.style) // R&B
    musician.introduce() // My name is jinchuu, I'm R&B vocal!
    musician.sing() // shubidubap~~~

    댓글

Designed by Tistory.