ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 객체 지향 프로그래밍(2) - prototype이 필요한 이유
    JavaScript 2020. 6. 19. 22:12

    모든 함수에는 prototype이라는 속성이 있다. prototype을 이용하면 생성자가 만든 모든 객체가 공통적으로 사용하는 속성을 만들 수 있다.

    function Person(name, first, second, third){
      this.name = name;
      this.first = first;
      this.second = second;
    }
    
    // Person이라는 생성자 함수의 prototype(원형)에 sum이라는 함수를 정의하는 과정
    Person.prototype.sum = function(){
      return `${this.name} sum() : ${this.first + this.second}`; 
    }
    
    let kim = new Person('kim', 10, 20);
    let lee = new Person('lee', 10, 20);
    console.log(kim.sum()); // kim sum() : 30
    console.log(lee.sum()); // lee sum() : 20

    위와 같이 생성자 함수 Person 안에서 함수 sum을 정의하지 않고, Person의 prototype에 sum이라는 함수를 정의하면, 생성자 Person은 new 키워드를 통해 새로운 객체(인스턴스)를 만들어질 때마다 sum 함수를 정의하는 코드를 실행하지 않아도 된다. 즉, 코드의 재사용성과 성능을 향상시킬수 있다. 아무리 많은 인스턴스를 만든다해도 모든 인스턴스에서 함수 sum을 공유할 수 있는 것이다.

     

    만일, Person 생성자를 이용해서 여러 개의 인스턴스를 만드는데 그중 하나의 인스턴스에서만큼은 sum 함수를 다르게 사용하고 싶다면?

    function Person(name, first, second, third){
      this.name = name;
      this.first = first;
      this.second = second;
    }
    
    // Person이라는 생성자 함수의 prototype(원형)에 sum이라는 함수를 정의하는 과정
    Person.prototype.sum = function(){
      return `${this.name} sum() : ${this.first + this.second}`; 
    }
    
    let kim = new Person('kim', 10, 20);
    kim.sum = function(){ // 객체 kim에 sum이라는 메소드를 정의하고 있다.
      return `my sum is ${this.first + this.second}!`;
    }
    
    let lee = new Person('lee', 10, 20);
    let park = new Person('park', 10, 40);
    
    console.log(kim.sum()) // my sum is 30!
    console.log(lee.sum()) // lee sum() : 30
    console.log(park.sum()) // park sum() : 50

    결과를 통해 prototype의 특징을 알 수 있는데, 자바스크립트는 객체(kim)의 메서드(sum)를 호출할 때, 제일 먼저는 그 객체 자신이 해당 속성(여기서는 메서드)을 가지고 있는지를 확인한다. 여기서는 객체 kim에 sum메서드를 직접 정의해 주었기 때문에 그것을 찾아서 실행한 것이다. 객체 lee와 park는 자체적으로 메서드 sum을 가지고 있지 않기 때문에, 자신의 생성자인 Pesron의 prototype에서 sum 메서드를 찾아서 실행한다.

     

    댓글

Designed by Tistory.