Javascript Class

MAX GUN·2021년 6월 19일
0

Javascript Class

1.Javascript Class는 일반 생성자 함수와 다른가?

아니다. Javascript Class는 프로토타입 패턴을 Class 기반처럼 동작하도록 만든것이다. 일반적으로 Java 개발자들이 프로토타입이라는 개념 자체가 낯설기 때문에 객체지향의 Class 처럼 보이도록 만든것이라고 볼 수 있다.

2.생성자 함수 와 Class 비교

생성자 함수

const Person = (function () {
  //생성자 함수
  function Person(name, country) {
    this.name = name;
    this.country = country;
  }

  // 프로토타입 메소드
  Person.prototype.sayHello = function () {
    return `HELLO ${this.name} I am from ${this.country}`;
  };

  // 정적 메소드
  Person.staticMethod = function () {
    return `this is staticMethod`;
  };

  return Person;
})();

const person1 = new Person("CHOI DAE GEON", "KOREA");

Class

class Person {
  //생성자 함수
  constructor(name, country) {
    this.name = name;
    this.country = country;
  }

  // 프로토타입 메소드
  sayHello() {
    return `HELLO ${this.name} I am from ${this.country}`;
  }

  // 정적 메소드
  static staticMethod() {
    return `this is staticMethod`;
  }
}

const person1 = new Person("CHOI DAE GEON", "KOREA");

각각의 생성자,프로토타입메소드,정적메소드를 표현하면 아래 그림과 같다.

3.생성자의 역할

위의 코드를 기반으로 설명하면 Person이라는 Class또는 생성자 함수를 통해
person1이라는 인스턴스를 만들었다. 여기서 인스턴스가 생성될 때
name,country를 값을 초기화 해줘야 하는데 여기서 이 값을 초기화 하는 것이 생성자의 역할이라고 볼 수 있다.

결론

결국 Javascript Class도 인스턴스를 생성하는 관점에서는 생성자 함수와 같다.
일반적이 객체지향 언어들 처럼 쓸 수 있도록 편하게 만든것이 Javascript Class라고 보면 될 것 같다.

profile
성장하는 프론트엔드 개발자

0개의 댓글