[Javascript] JS에서의 클래스와 생성자 함수와의 차이점

Re_Go·2024년 7월 24일
0

Javascript

목록 보기
37/44
post-thumbnail

1. Javascript의 클래스

JS에서도 자바와 마찬가지로 클래스가 존재하는데요. 다만 객체를 생성하는 경우는 거의 생성자 함수로 처리를 하다보니 잘 사용하지 않습니다만, 그래도 JS 또한 엄연히 클래스를 가지고 있답니다.

물론 양식도 자바의 클래스와 선언이나 사용법도 타입 선언을 제외한 나머지는 거의 똑같고요.

  1. 기본적인 클래스 정의
class Person {
        constructor(name) {
            this.name = name;
        }
        print() {
            console.log(`내 이름은 ${this.name} 입니다.`);
        }
}	
let kim = new Person('김씨');
kim.print();

  1. 기본적인 클래스의 상속
class Person {
  constructor(name) {
    this.name = name;
  }
  print() {
    console.log(`내 이름은 ${this.name}입니다.`);
  }
}

 class Student extends Person {
   constructor(name, age, school) {
     super(name);
     this.age = age;
     this.school = school;
   }

     print() {
     console.log(`${this.name}은(는) ${this.age}살이고, ${this.school}에 다닙니다.`);
   }
}

    // 인스턴스 생성 시 new 연산자를 사용합니다.
let student1 = new Student("장병태", 18, "상원고");
let student2 = new Student("정경태", 17, "마상고");

student1.print(); 
student2.print();

2. 생성자 함수와 다른 점

클래스는 생성자 함수와 비교했을 때 동적으로 객체를 생성한다는 점에서는 동일하나, 결정적 차이점이 존재하는데요. 바로 생성자 함수는 new 없이도 일반 함수로서 호출은 가능하나, 클래스는 new 키워드가 없으면 호출될 수 없다는 점입니다.

이는 ECMAScript에서 정의하고 있는 클래스의 [[IsclassConstructor]] 슬롯 때문인데요. 이 속성은 일반 함수의 경우 0, 그러니까 false로 선언되어 있어 굳이 new 키워드가 아니여도 호출될 수 있는 반면, 클래스의 경우 1, 즉 true로 설정되어 있느 new 키워드 없이 사용된 경우(false인 경우) 에러를 발생시키기 때문입니다.

function Person1(name) {
            this.name = name;
}
class Person2{
  constructor(name){
    this.name = name;
  }
}
const p1 = Person1("Alice"); // 생성자 함수는 new 없이도 호출 가능 (전역 변수로 추가됨)
console.log(name); // 'Alice'

const p2 = Person2("Bob"); // 클래스는 new 키워드가 없으면 호출 불가능
console.log(p2.name); // 오류 발생

profile
인생은 본인의 삶을 곱씹어보는 R과 타인의 삶을 배워 나아가는 L의 연속이다.

0개의 댓글