자바스크립트 클래스에 대한 정리

DONG EUN LEE·2024년 2월 10일

JavaScript

목록 보기
2/3
post-thumbnail

react 16.8이 나오기 전까지는 컴포넌트가 클래스로 작성이 되어 있다고 한다.
현재는 함수형태의 컴포너트를 작성하고있고, 종종 클래스형태로 작성된 컴포넌트들을 마주치는 경험도 있다. 이번 시간에는 자바스크립트의 클래스가 어떤식으로 동작하고 있는지 정리를 해보려고한다.

클래스(Class)란?

자바스크립트의 클래스란? 특정한 객체를 만들기 위한 일종의 템플릿과 같은 개념으로 볼 수 있다.
즉, 특정한 형태의 객체를 반복적으로 만들어내기 위해 사용하는 틀이라고 생각해 볼수 있다.

//클래스 객체의 선언 ex) Person 이라는 클래스를 선언     
class Person {
 //`constructor`는 생성자다. 최초에 생성할 때 어떤 인수를 받을지 결정이가능하고 객체를 초기화하는 용도로 사용
 constructor(name) {
   this.name = name;
 }


 // 객체에서 메서드를 정의할 때 사용하던 문법을 그대로 사용하면, 메소드가 자동으로 `Person.prototype`에 저장됩니다.
 introduce() {
   return `안녕하세요, 제 이름은 ${this.name}입니다.`;
 }
}
// 정적메서드
static hello{
	console.log('안녕하세요.');
}
// setter 
set age(value){
	this.age = value;
}

// getter
get age(){
	return this.age;
}
// 클래스를 활용하여 Person 객체 생성
const dongeun = new Person('dongeun');

//메서드 호출
dongeun.introduce(); // 안녕하세요, 제 이름은 dongeun 입니다.

// 정적 메서드는 클래스에서 직접호출한다.
Person.hello(); // 안녕하세요.

// 정적 메서드는 클래스로 만든 객체에서는 호출할 수 없다.
dongeun.hello(); //Uncaught TypeError: dongeun.hello is not a function

// setter를 통해 값을 할당할 수 있다.
dongeun.age = 28;

// getter를 통해 값을 가져올 수 있다.
console.log(dongeun.age); // 28

constructor란?

constructor는 생성자로 , 객체를 생성하는데 사용되는 메서드이며, 여러개가 존재할수 없고 별다르게 수행할 작업이 없다면 생략도 가능하다.

// X
class Person {
 constructor(name) {
   this.name = name;
 }
 // SyntaxError: A class may only have one constructor
 constructor(name) {
   this.name = name;
 }
}

// O
class Person {
}

프로퍼티(property)란?

property란 클래스로 인스턴스를 생성할 때 내부에 정의할 수 있는 속성값으로 일반적으로 내부 변수와 그 변수에 접근하는 메소드(getter 및 setter)로 구성되며, 이를 통해 외부에서 해당 프로퍼티에 접근할 때 특정 로직을 실행하거나 값을 검증할 수 있다.

getter

클래스에서 무언가 값을 가져올때 사용되고, 사용하기 위해서 get이라는 키워드를 앞에 붙여야하고, 뒤이어서 getter의 이름을 선언한다.

setter

클래스 필드에 값을 할당할때 사용한다. set 이라는 키워드를 선언하고, 그 뒤에 이름을 붙인다.

class Person {
    constructor(name, age) {
        // 프로퍼티 정의
        this._name = name; // private 프로퍼티 (관례적으로 _를 사용)
        this._age = age; // private 프로퍼티
    }

    // Getter와 Setter 메소드
    get name() {
        return this._name;
    }

    set name(newName) {
        this._name = newName;
    }

    get age() {
        return this._age;
    }

    set age(newAge) {
        if (newAge > 0) { // 나이는 음수가 될 수 없도록 설정
            this._age = newAge;
        } else {
            console.log("나이는 음수가 될 수 없습니다.");
        }
    }
}

// 예시 사용
const dongeun = new Person('dongeun', 28);
console.log(dongeun.name); // 출력: dongeun
console.log(dongeun.age); // 출력: 28

dongeun.age = -5; // 음수 나이를 설정하려고 하면 에러 메시지 출력
console.log(dongeun.age); // 출력: 28 (변경되지 않음)

dongeun.age = 35; // 올바른 나이를 설정
console.log(dongeun.age); // 출력: 35

처음에 예시로 작성했던 코드와 비교를 해보았을때 name 프로퍼티를 선언할때 _name으로 선언한것을 볼 수 있다.
_name과 같은 네이밍 컨벤션은 자바스크립트에서 private 프로퍼티를 나타내는데 일반적으로 사용되는 관례하고 한다고 한다. 이는 명시적으로 private 프로퍼티를 지원하는 것이 아니라, 개발자들 사이에 널리 사용되는 약속이며, 주로 다른 개발자들이 private 프로퍼티임을 파악할 수 있도록 돕기 위한 목적으로 사용된다.

상속(extends)

상속은 기존의 클래스를 상속받아서 자식 클래스에서 부모클래스를 상속 받는 개념이다.
React에서 클래스형 컴포넌트를 만들기위해서 extends React.component 나 extends React.PuerComponent 를 선언한 것을 예시로 들 수 있다.

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    get name() {
        return this._name;
    }

    set name(newName) {
        this._name = newName;
    }

    get age() {
        return this._age;
    }

    set age(newAge) {
        if (newAge > 0) {
            this._age = newAge;
        } else {
            console.log("나이는 음수가 될 수 없습니다.");
        }
    }
}

class Employee extends Person {
    constructor(name, age, position, salary) {
        super(name, age); // 부모 클래스의 생성자 호출
        this._position = position;
        this._salary = salary;
    }

    get position() {
        return this._position;
    }

    set position(newPosition) {
        this._position = newPosition;
    }

    get salary() {
        return this._salary;
    }

    set salary(newSalary) {
        this._salary = newSalary;
    }
}

// 예시 사용
const employee1 = new Employee('dongeun', 28, 'Front-end Engineer', 60000);
console.log(employee1.name); // 출력: dongeun
console.log(employee1.age); // 출력: 28
console.log(employee1.position); // 출력: Front-end Engineer
console.log(employee1.salary); // 출력: 60000

0개의 댓글