ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 객체 - new 연산자와 생성자 함수
    Javascript 2021. 7. 3. 18:03

    객체 리터럴 {}을 사용하면 객체를 쉽게 만들 수 있지만 유사한 객체를 여러 개 만들어야 할 때가 생기곤 한다. 이럴때 new 연산자와 생성자 함수를 사용하면 유사한 객체 여러 개를 쉽게 만들 수 있다.

     

     

    생성자 함수는

    1. 함수 이름의 첫 글자를 대문자로 한다.

    2. 반드시 new 연산자를 붙여 실행한다.

     

    예시:

    function User(name) {
      // this = {}; 빈 객체가 암시적으로 만들어진다.
      this.name = name;
      this.isAdmin = false;
      
      // return this; this가 암시적으로 반환된다.
    }
    
    let user = new User("보라");
    
    alert(user.name); // 보라
    alert(user.isAdmin); // false

    new User()을 써서 함수를 실행하면 아래와 같은 알고리즘이 동작한다.

    1. 암시적으로 빈 객체를 만들어서 this에 할당한다.

    2. 함수 본문을 실행하면서 this에 새로운 프로퍼티를 추가하면서 this를 수정한다.

    3. 암시적으로 this를 반환한다.

     

     

    생성자와 return 문

    생성자 함수에는 보통 return문이 없다. 반환해야 할 모든 정보가 this에 저장되고, this는 자동으로 반환되기 때문이다.

    하지만 return 문이 있다면 다음과 같은 규칙이 적용된다.

    1. 객체를 return한다면 this 대신 객체가 반환된다.

    2. 원시타입을 return한다면 원래대로 this가 반환된다.

     

     

    생성자 내 메서드

     

    function User(name) {
      this.name = name;
    
      this.sayHi = function() {
        alert( "제 이름은 " + this.name + "입니다." );
      };
    }
    
    let bora = new User("이보라");
    
    bora.sayHi(); // 내 이름은 이보라입니다.
    
    /*
    bora = {
       name: "이보라",
       sayHi: function() { ... }
    }
    */

    sayHi 메서드도 프로퍼티처럼 this.를 붙여서 더해줄 수 있고 sayHi 내부에서도 this.name으로 this 내부의 name 프로퍼티를 가져올 수 있다.

     

     

    문제

     

    1. 계산기 만들기

     

    아래와 같은 세 개의 메서드를 가진 생성자 함수, Calculator를 만들어보세요.

    • read()   prompt 함수를 이용해 사용자로부터 값 두 개를 받고, 이를 객체 프로퍼티에 저장합니다.
    • sum() – 프로퍼티에 저장된 값 두 개를 더한 후 반환합니다.
    • mul() – 프로퍼티에 저장된 값 두 개를 곱한 후 반환합니다.
    function Calculator() {
        this.a,
        this.b,
        this.read = function() {
            this.a = +prompt('값 입력','') || '0';
            this.b = +prompt('값 입력','') || '0'; 
        };
    
        this.sum = function() {
            return this.a + this.b;
        };
    
        this.mul = function() {
            return this.a * this.b;
        };
    }
    
    let calculator = new Calculator();
    calculator.read();
    
    alert( "Sum = " + calculator.sum());
    alert( "Mul = " + calculator.mul());
    

     

    2. 누산기 만들기

     

    생성자 함수 Accumulator(startingValue)를 만들어 보세요.

    Accumulator(startingValue)를 이용해 만드는 객체는 아래와 같은 요건을 충족해야 합니다.

    • 프로퍼티 value에 현재 값(current value)을 저장합니다. 최초 호출 시엔 생성자 함수의 인수, startingValue에서 시작값(starting value)을 받아옵니다.
    • 메서드 read()에선 prompt 함수를 사용해 사용자로부터 숫자를 받아오고, 받은 숫자를 value에 더해줍니다.

    프로퍼티 value엔 startingValue와 사용자가 입력한 모든 값의 총합이 더해져 저장됩니다.

    function Accumulator(startingValue) {
        this.value = startingValue;
        this.read = function() {
            this.a = +prompt('숫자 입력','');
            this.value +=this.a;
        };
    }
    
    let accumulator = new Accumulator(1);
    
    accumulator.read();
    accumulator.read();
    
    alert(accumulator.value);

     

     

Designed by Tistory.