[Javascript] 정적 메서드와 프로토타입 메서드의 특징과 차이

hello__0·2022년 11월 10일
0

Javascript-Class

목록 보기
7/7

Class는 3가지의 메서드를 가진다.

  1. 생성자
  2. 정적 메서드
  3. 프로토타입 메서드

class Person {
  // 생성자
  constructor(name) {
    this.name = name;
    this.age = 16;
    this.job = "developer";
  }
  // 프로토타입 메소드
  introduce() {
    return `Hello, my name is ${this.name} and I'm ${this.age}years old.`;
  }
  // 정적 메소드
  static country() {
    return `I'm living in Toronto`;
  }
}
const person = new Person("우기");

정적 메소드와 프로토타입 메소드의 차이

정적 메소드 : 인스턴스의 프로토타입 체인에 속해있지 않다.

  • 클래스로 호출
  • 인스턴스의 프로퍼티를 참조하지 않는다.
    정적 메소드는 클래스로 호출되기 때문에 this를 사용할 수 없다.
Person.country();

프로토타입 메소드

  • 인스턴스 호출
  • 인스턴스의 프로퍼티를 참조한다.
  • this를 사용할 경우엔 프로토타입 메소드로 정의하면 된다.
const person = new Person('우기');
person.introduce();

참고 : https://seo-tory.tistory.com/80

profile
자라나라 나무나무

0개의 댓글