js의 클래스

NANA·2023년 7월 24일
0

출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

일단.. 일단 자바의 그 클래스처럼 생각을 하는 것이 이해가 빠를 듯 싶다.

기존 js 함수와의 차이?

  • 함수는 호이스팅링크텍스트 대상이지만 클래스는 반드시 정의한 뒤에 사용할 수 있다.

class 표현식

// unnamed
let Rectangle = class {
  
  // 생성자 - class로 생성된 객체를 생성하고 초기화 하기 위한 메소드
  // 한 클래스 안에 한개만 존재해야한다. 부모 생성자 호출을 위해 super 사용 가능
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle"

// named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle2"

저 Rectangle이라는 name은 클래스 body의 local scope에 한해 유효하답니다..

static

자바랑 비슷하게 이해하면 됨
인스턴스화 하지 않고 호출이 가능해진다.
클래스.static인애 --> 이렇게 호출 가능하다는 뜻

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static displayName = "Point";
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.hypot(dx, dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.displayName; // undefined 감히 인스턴스 따위가
p1.distance;    // undefined
p2.displayName; // undefined
p2.distance;    // undefined

console.log(Point.displayName);      // "Point"
console.log(Point.distance(p1, p2)); // 7.0710678118654755
profile
일단 나만 알아보면 된다는 마음으로, 작더라도 꾸준히

2개의 댓글

comment-user-thumbnail
2023년 7월 25일

공감하며 읽었습니다. 좋은 글 감사드립니다.

1개의 답글