본문 바로가기

JavaScript

2023.12.23 기록 (JS 객체와 배열 1. 생성자 함수)

26일 Firebase의 구현을 위해서는 for문과 배열내의 for문, 그리고 객체에 관해서 조금 더 깊은 이해가 필요했다.

 

학습 중 가장 먼저 생성자 함수에 대한 정보를 정리해봤다.

 

생성자 함수의 함수명은 항상 대문자로 작성하고, 호출시에는 new를 붙여서 진행한다.

 

    function Reverse1999(name, role) {
        this.name = name;
        this.role = role;
        this.introduce = function () {
            return `캐릭터 ${this.name}은 ${this.role}의 역할을 수행합니다!`;
        }
    }

    const question1 = new Reverse1999('void', 'support');
    const question2 = new Reverse1999('sonetto', 'support');
    console.log(question1, question1.introduce());
    console.log(question2, question2.introduce());

 

 

new 연산자를 이용해서 새로운 객체를 생성 할 때마다

각각의 name과 role을 정의하고 introduce의 함수를 실행하는데, 이때 introduce의 역할은 앞으로 생성될 Reverse1999 객체에서 항상 같은 역할을 수행하게 된다. (소개문을 작성하는)

 

즉 중복되는 문장이 계속 만들어지는 것이다. 

그래서 이 부분을 프로토타입으로 정의한다면, 객체 전역에 영향을 미칠 수 있을 것이다. 따라서 다음과 같이 문장을 수정했다.

 

 

 

    function Reverse1999(name, role) {
        this.name = name;
        this.role = role;
    }
    Reverse1999.prototype.introduce = function () {
        return `캐릭터 ${this.name}은 ${this.role}의 역할을 수행합니다!`;
    };

    const question1 = new Reverse1999('void', 'support');
    const question2 = new Reverse1999('sonetto', 'support');
    
    console.log(question1); 
    console.log(question1.introduce());
    console.log(question2); 
    console.log(question2.introduce());

 

이렇게 진행한다면, 객체마다 introduce가 들어가지 않기때문에 중복되는 부분을 조금 더 줄일 수 있게 된다.

 

 

 

 console.log(question1); 
 console.log(question1.introduce());
//
 console.log(question1, question1.introduce());

 

그 외에도

 

위와 아래의 console 호출은 같은 내용을 호출하지만, 문제가 발생했을 때 디버깅을 용이하기 하기 위해서

분할해서 작성하는게 권장된다고 한다.