티스토리 뷰

상속(inheritance)이란? 

객체는 연관된 로직들(변수, 메소드)로 이루어진 작은 프로그램이라고 할 수 있다.

  • 상속은 객체의 로직을 그대로 물려 받는 또 다른 객체를 만들 수 있는 기능을 의미한다. -> 로직 재활용 가능
  • 단순히 물려받는 것이 아니라 기존의 로직을 수정하고 변경해서 파생된 새로운 객체를 만들 수 있게 해준다. 
	//이전에 생성자를 통해 객체를 만드는 방법
	//생성자 함수의 내부에 프로퍼티를 정의하고 있다.
      //   function Person(name) {
      //     this.name = name;
      //     this.introduce = function () {
      //       return "My name is " + this.name;
      //     };
      //   }
      //   const p1 = new Person("cong");
      //   document.write(p1.introduce() + "<br />");

    /*위의 코드를 수정한 코드 - Person(생성자 함수이자 객체)의 
     내장 프로퍼티인 prototype(이 내부에 어떤 객체가 들어가있다)을 사용하여 만들기 */
      function Person(name) {
        this.name = name;
      }
       //생성자 함수 외부에 prototype을 사용하여 프로퍼티를 정의
      Person.prototype.name = null;
      Person.prototype.introduce = function () {
        return "My name is " + this.name;
      };
      const p1 = new Person("egoing");
      document.write(p1.introduce() + "<br />");

상속의 사용방법

// Person 생성자
      function Person(name) {
        this.name = name;
      }
      Person.prototype.name = null;
      Person.prototype.introduce = function () {
        return "My name is " + this.name;
      };
      //Programmer 생성자
      function Programmer(name) {
        this.name = name;
      }
      Programmer.prototype = new Person(); //상속관련 코드 
      const p1 = new Programmer("cong");
      document.write(p1.introduce() + "<br/>");
      
    /*1. new Programmer("cong")이 실행
      2. function Programmer(name)함수에 cong이 인자로 들어오고 this.name = cong;, this.name에 cong을 담아준다
      name이라는 프로퍼티의 값이 cong .
      3. new와 생성자함수로 생긴 객체를 p1에 담는다. 
      4. p1.introduce()를 하면 introduce()메소드가 실행된다 정의하지도 않았는데 어떻게 작동? 
      상속을 받았기 때문이다 */
  • Person함수는 이전의 예시 코드에 미리 정의해놨던 생성자 함수이다. 우리는 이 Person의 프로퍼티를 상속하는 객체를 만들어보고자 한다. 
  • prototype과 Person의 객체를 연결했더니 Programmer 객체도 메소드 introduce를 사용할 수 있게 되었다. 
  • Programmer가 Person의 기능을 상속하고 잇는 것이다. 아예 같은 것이 아니라 부모의 기능을 계승 발전할 수 있는 것이 상속의 가치이다. 
  • 아래는 상속관련 코드 설명 
    1.  Programmer.prototype = new Person()에서 new Person()을 하게되면 생성자함수는 객체를 생성
    2. 제대로 이해한 지는 잘 모르겠으나 Person의 속성을 담은 객체가 prototype에 담겨있기 때문에 new Person을 통해 만든 객체 역시 속성으로 name과 introduce를 가지고 있게된다.
    3. 이전에 만든 객체가 Programmer.prototype라는 프로퍼티의 의 값이 되는 것이죠.
    4. p1은 prototype이라는 생성자의 프로퍼티에 담겨있는 객체와 같은데 그 객체는 new Person을 통해서 만들어지는 객체라서 name과 introduce라는 프로퍼티를 가지고 있으며 p1.introduce()가 가능하게 되는 것이다.

상속을 통해 기능 추가

 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 "I am a programmer!";
      };
      function Designer(name) {
        this.name = name;
      }
      Designer.prototype = new Person();
      Designer.prototype.desing = function () {
        return "I am a desinger";
      };

      const p1 = new Programmer("cong");
      const p2 = new Designer("kang");
      document.write(p2.introduce() + "</br>");
      document.write(p2.desing() + "<br/>");
      document.write(p1.introduce() + "<br/>");
      document.write(p1.coding() + "</br>");

prototype

  • 상속의 구체적인 수단
  • 한국어로 "원형" 정도로 번역된다. -> 말 그대로 객체의 원형이라고 할 수 있다. 
  • JS에서 함수는 객체이기 때문에 생성자로 사용될 함수 역시 객체이다.
  • 객체는 프로퍼티를 가질 수 있는데 prototype이라는 그 용도가 약속되어 있는 특수한 프로퍼티이다.
  • prototype에 저장된 속성들은 생성자를 통해서 객체가 만들어질 때 그 객체에 연결된다. / 객체와 객체를 연결하는 체인의 역할을 하는 prototype-> 이 연결을 prototype chain 이라고 합니다. 
      function Ultra() {}
      Ultra.prototype.ultraProp = true;

      function Super() {}
      Super.prototype = new Ultra();

      function Sub() {}
      Sub.prototype = new Super();

      const o = new Sub();
      console.log(o.ultraProp);

-> 결과적으로 prototype chain에 의하여 객체 o에서 Ultra객체의 ultraProp이라는 프로퍼티에 접근할 수 있다.

 

내부적인 작업 흐름

  1. 객체 o에서 ultraProp 찾기 
  2. 없다면 Sub.prototype.ultraProp 찾기 
  3. 없다면 Super.prototype.ultraProp 찾기
  4. 없다면 Ultra.prototype.ultraProp  찾기

Super.prototype = Ultra.prototype 으로하면 안된다. 이렇게하면 Super.prototype의 값을 변경하면 그것이 Ultra.prototype도 변경하기 때문이다. Super.prototype = new Ultra();는 Ultra.prototype의 원형으로 하는 객체가 생성되기 때문에 new Ultra()를 통해서 만들어진 객체에 변화가 생겨도 Ultra.prototype의 객체에는 영향을 주지 않는다.

  • 예로들면 Person.prototype.getName = ~의 뜻은 Person이라는 원형에 getName라는 것을 넣을거라는 의미 복사하여 다른 변수에 넣고 사용해도 getName메소드를 사용할 수 있게 됩니다. prototype을 쓰지 않고 Person.getName을 쓴다는 건 그냥 메소드를 만들겠다는 것

 

 

프로토타입 관련 링크 

https://www.tutorialsteacher.com/javascript/prototype-in-javascript 

 

Prototype in JavaScript

Prototype in JavaScript JavaScript is a dynamic language. You can attach new properties to an object at any time as shown below. function Student() { this.name = 'John'; this.gender = 'Male'; } var studObj1 = new Student(); studObj1.age = 15; alert(studObj

www.tutorialsteacher.com

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

 

Inheritance and the prototype chain - JavaScript | MDN

JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in ES2015, but is syntactical sugar, JavaScript remai

developer.mozilla.org

 

댓글