본문 바로가기
개발공부일지/JavaScript

JavaScript - Class 함수 (Feat.생성자 함수/Template)

by Hynn1429 2023. 1. 9.
반응형

안녕하세요.

이번 포스팅에서는 Class 의 대한 기본개념, 사용에 대한 학습을 위한 포스팅을 작성해보겠습니다.

생성자 함수이기도 한 Class 는 활용하기에 따라서 코드의 대한 분리 및 작성이 매우 용이하다고 할 수 있습니다.

 

시작해보도록 하겠습니다.

 

=============

1. Class는 무엇인가요?

2. Class 기본 작성 및 주의점

3. Class 상속 사용

=============

1. Class는 무엇인가요?

Class 는 일종의 "Form" 입니다. 

이 Class 는 "생성자 함수" 라고도 합니다. 한마디로, 객체를 생성하는 템플릿입니다. SQL 과 같이 일정하게 정해진 방식의 객체를 생성해야할 때 매우 유용합니다. 

 

가장 기초적으로 아래의 형태로 작성한 Class 를 살펴보도록 하겠습니다.

 

class Dog {
    constructor(name,age,model,gender) {
        this.name = name;
        this.age = age;
        this.model = model;
        this.gender = gender;
    }
}

const dog1 = new Dog('Hynn',2,'Dog','Male')
const dog2 = new Dog('Blog',3,'Dog','Female')

이렇게 Class 를 이용해 생성한 dog1, dog2 는 자동으로 Class 생성자 함수를 이용해 객체의 양식을 제공하여, 값만을 할당하여 하나의 객체로 생성할 수 있습니다.

실제 이를 Console.log 로 출력하면 쉽게 확인이 가능합니다.

또한 이 객체들의 특정 인스턴스 값을 불러오려면 ".표기"를 사용해 가져올 수도 있습니다.

 

생성자 함수는, 이렇게 정해진 양식을 사용하여 객체형태로 저장할 때 유용합니다. 즉 구조화된 데이터에는 생성자함수를 이용해 템플릿을 생성해두면, 이 생성된 템플릿을 이용해서 값을 쉽게 추가할 수 있습니다.

 

2. Class 기본 작성 및 주의점

Class 함수의 경우 몇가지 사용에 조건이 존재합니다.

이것이 기본 사용법입니다.

 

1) constructor 사용하기

Constructor 는 Class 함수의 기본 사용법의 토대가 됩니다.

위의 기본 예시에도 작성했듯이, Class 함수를 선언하면, 함수 내에 Constructor 을 사용하면 Class 함수를 통해 생성된 객체를 생성하고 초기화하는 "Method" 입니다.

이 Method 는 Class 함수 당 1번만 사용이 가능합니다. 여러개의 Class 함수를 사용할 수는 있지만, 함수 당 1번만 사용이 가능한 점은 꼭 기억해야 합니다. 

class HumanInfo {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  get total() {
    return this.calclator();
  }
    caculator() {
    return this.height * this.width;
  }

 

위의 예제 함수를 살펴보도록 하겠습니다.

Class 함수에서 먼저 Constructor 를 사용해서, "HumanInfo" 라는 생성자 함수 내에 "height", "width" 라는 두개의 인스턴스(Instance) 를 생성했습니다. 여기서 함수에서 상당히 등장하는 this" 에 대해서도 잘 알아야 합니다.

 

"this" 의 경우 아래의 두가지를 염두에 두시면 사용에 도움이 됩니다.

1) 전역에서 실행시
console.log (this === window)

먼저 this 는 전역에서 사용시, 반드시 window object 를 참조합니다. 즉, 전역에서는 "window.~" 대신 "this.~" 로 사용이 가능합니다.

하지만 이 경우 사용에 큰 의미가 있다고 보기 어렵습니다. 물론 다른 방식으로도 사용이 가능합니다.

자세한 정보는 "MDN Web Docs - About this" 에서 자세한 정보를 확인할 수 있습니다. (*작성자는 영어 버전을 권장합니다.)

 

하지만 예제 코드에서의 "this" 는 바로 자신의 실행중인 Function(함수)/Object(객체)를 참조합니다.

즉 Class Function 내에서 사용된 "this" 는 바로 Class function 을 참조하므로, 작성이 보다 직관적이라고 할 수 있습니다.

class MyClass {
  static staticProp = Hynn
  instanceProp = Hyunsignblog.tistory.com


  static staticMethod() {
    console.log(this.staticProp);  
}

  instanceMethod() {
    console.log(this.instanceProp);  
  }

  constructor() {
    console.log(this.instanceProp);

 

각 유형별로 위와 같이 정리해볼 수 있습니다.

1,2번에 사용된 This 의 경우, constructor 바깥에 정의한 Static, instance 의 경우, 그 자체를 참조하므로, Console.log 에서는 각각 

"Hynn", "Hyunsignblog.tistory.com" 이 출력됩니다.

 

하지만 Constructor 를 사용하여 생성할 경우 "Instance" Object, 즉 객체를 참조합니다. 

위 차이를 구분하면 This 사용을 올바르게 할 수 있습니다.

 

3. Class 상속 사용

하지만, Class 는 "재정의"가 불가능하다는 점이 있습니다.

이러한 특징을 보완하기 위해 "상속" 이라는 개념을 적용할 수 있습니다.

 

즉, A,B 의 Class 를 이용해 예시를 작성해보겠습니다.

class A {
    constructor(){
        this.key = key;
        this.value = value;
    }
}


class B extends A {
    constructor(){
    	super()
        this.height = height;
        this.width = width;
    }
}

const a = new A('myKey', 'myValue');
console.log(a.key);  
console.log(a.value);  

const b = new B('myKey', 'myValue', 100, 200);
console.log(b.key);  
console.log(b.value);  
console.log(b.height); 
console.log(b.width);

각각의 Class 에서 key,value, height, width 를 Instance으로 부여했습니다. 

여기서 A 는 기존의 선언방식과 동일하며, 다를필요가 없습니다.

 

하지만 B의 경우, A의 Class 생성자 함수를 상속하기 위해서 "extends" 를 사용해 작성하면, B 에서도 A의 key,value 를 사용할 수 있습니다.

이렇게 할 경우, 3가지의 유의점이 필요합니다.

 

  • constructor 와 super 의 매개변수는 같아야 합니다.

위의 예제 구문은 constructor 의 매개변수가 부여되지 않았습니다.

따라서, super 역시 매개변수를 생략할 수 있습니다.

하지만 만약 constructor 에 매개변수가 부여되었다면, super 역시 동일한 매개변수가 부여되어야 합니다.

이를 예시로 작성하면 아래와 같습니다.

 

 

잘못된 작성의 예

class A {
    constructor(key,value){
        this.key = key;
        this.value = value;
    }
}


class B extends A {
    constructor(){
    	super()
        this.height = height;
        this.width = width;
    }
}

const a = new A('myKey', 'myValue');
console.log(a.key);  
console.log(a.value);  

const b = new B('myKey', 'myValue', 100, 200);
console.log(b.key);  
console.log(b.value);  
console.log(b.height); 
console.log(b.width);

올바른 작성의 예

class A {
    constructor(key,value){
        this.key = key;
        this.value = value;
    }
}


class B extends A {
    constructor(){
    	super(key,value)
        this.height = height;
        this.width = width;
    }
}

const a = new A('myKey', 'myValue');
console.log(a.key);  
console.log(a.value);  

const b = new B('myKey', 'myValue', 100, 200);
console.log(b.key);  
console.log(b.value);  
console.log(b.height); 
console.log(b.width);

 

  • 상속된 Class 함수 구문에는 "super()" 가 작성되어야 합니다.

예시 구문에서 B는 A의 상속(B는 A의 자녀)된 Class 문법으로 작성되었습니다.

하지만 여기서 super() 를 작성하지 않을 경우, B는 A의 Instance에 접근할 수 없기 때문입니다.

 

super 의 역활은 명료하지만, 중요한 역활을 하고 있기 때문입니다.

super() 를 먼저 작성을 함으로서, 상속된 Class B 에서 상속체인 (inheritance chain) 을 설정하고, this 하위 클래스의 값을 초기화함으로서 상속연결이 완료되기 때문입니다.

 

혹시라도 상속된 Class 에서 접근이 되지 않을 경우, 가장 먼저 확인해야할 사항은 Super() 입니다.

 

  • 두 개의 Class 에 중복된 Instance 가 존재할 경우, 호출한 Class 의 Instance 를 호출합니다.
class A {
    constructor(key,value,height){
        this.key = key;
        this.value = value;
        this.height = height
    }
}


class B extends A {
    constructor(){
    	super(key,value)
        this.height = height;
        this.width = width;
    }
}

const a = new A('myKey', 'myValue', 10);
console.log(a.key);  
console.log(a.value);
console.log(a.height);

const b = new B('myKey', 'myValue', 100, 200);
console.log(b.key);  
console.log(b.value);  
console.log(b.height); 
console.log(b.width);

위와 같이 정상적으로 Instance 를 부여할 경우, B 에서는 상속된 A의 Instance 를 참조할 수 있습니다.

하지만, "height" 의 경우 A,B 모두에 존재합니다.

이러한 경우, A는 당연히 상속을 받지 않았으므로, A 에서는 올바르게 호출됩니다.

하지만 B 에서는 호출할 때, A 의 값을 참조하더라도, 최종결과는 "B" 에 정의된 100을 출력합니다.

 

============================================

Class 생성자를 통해 코드를 작성한다면, 몇가지 이점이 존재합니다.

가령 예를 들어, JavaScript 를 사용하여, express web server 를 구현할 때, manual 방식을 사용하여 HTML Element 에 지정된 양식에 값을 넣는 방식을 취했다면, 생성자 함수를 이용한 "추상화" 개념에 접근하여 사용시, 일종의 Template 화 하여 사용이 가능합니다.

 

다음 포스팅에서는 실제 Class 함수를 이용해 간단한 실습을 하면서 코드를 리뷰해보도록 하겠습니다.

감사합니다.

반응형

댓글