class

김형진·2024년 8월 13일
post-thumbnail

Javascript의 class 는 객체(Object)와 관련이 있음.

객체를 직접 작성하여 정의하고 생성할 수도 있지만, 클래스로 만들어주면 여러 객체를 더 쉽게 만들 수 있음.

클래스는 객체를 생성하기 위한 템플릿

Constructor

  • constructor(생성자)를 사용하면 인스턴스화된 객체에서 다른 메서드를 호출하기 전에 수행해야하는 사용자 지정 초기화 제공
  • 클래스를 new를 붙여서 인스턴스 객체로 생성하면 넘겨 받은 인수와 함께 constructor가 실행
class Person {
  constructor(name, email, birthday) {
    this.name = name;
    this.email = email;
    this.birthday = new Date(birthday);
  }
  introduce() {
    return `Hello my name is ${this.name}`;
  }

  static multipleNumbers(x, y) {
    return x * y;
  }
}

const John = new Person("john", "test@test.com", "10-3-98");
console.log(John);
/*Person {
    name: 'john',
    email: 'test@test.com',
    birthday: 1998-10-02T15:00:00.000Z
  }*/
console.log(John.introduce());
//Hello my name is john
console.log(John.constructor.multipleNumbers(1, 3));
//3

위 코드 작동 시 introduce함수는 prototype에 정의된다.

static multipleNumbers 함수는 class Person의 프로퍼티가 된다.

static 키워드를 사용하여 메소드를 정의하면

new "클래스이름"으로 인스턴스 객체를 생성하지 않아도 해당
메소드를 사용할 수 있다는 장점이 있다.

sub class

  • 부모 클래스를 자식 클래스에 확장할 수 있다
  • 부모 클래스에 있던 기능을 토대로 자식 클래스를 만들 수 있는 것
  • extend 사용

super()

  • 자식 클래스 내에서 부모 클래스의 생성자를 호출할 때 사용
  • 자식 클래스 내에서 부모 클래스의 메소드를 호출할 때 사용
class Person {
  constructor(name, email, birthday) {
    this.name = name;
    this.email = email;
    this.birthday = new Date(birthday);
  }
  introduce() {
    return `Hello my name is ${this.name}`;
  }
}

class Client extends Person {
  constructor(name, email, phone, address) {
    super(name, email); //부모 클래스에서 생성자 호출
    this.phone = phone;
    this.address = address;
  }
  phoneNumber() {
    return super.introduce() + `, my phone ${this.phone}`;//부모 클래스의 메소드 호출
  }
}

const John = new Client("john", "test@test.com", "010-1234-1234", "Jinju");
console.log(John);
/*Client {
  name: 'john',
  email: 'test@test.com',
  birthday: Invalid Date,
  phone: '010-1234-1234',
  address: 'Jinju'
}*/
console.log(John.introduce());
//Hello my name is john
console.log(John.phoneNumber());
//Hello my name is john, my phone 010-1234-1234

위 관계도를 확인하면 Client는 Person에서 확장해서 제작한 class이다. 두 class의 prototype은 연결되어 있고 코드에서 John.introduce함수가 사용 가능한 것이다.

John.introduce가 실행되는 순서

  1. Client 객체에 Client.introduce가 있는지 확인
  2. 없기 때문에 Client.prototype에 있는지 확인
  3. Client.prototype에도 없어서 extends를 통해 관계가 만들어진 Client.prototype의 프로토타입인 Person.prototype에 메서드 있는지 확인
  4. 존재하므로 사용

0개의 댓글