[JavaScript] 클래스(class) 다양한 문법

iberis2·2023년 1월 15일
0

[JavaScript] 클래스(Class)와 인스턴스(instance)
[JavaSript] 객체의 접근자 프로퍼티 get(){}, set(){}
[JavaScript] 클래스 확장하기(extends), 덮어쓰기(overriding), super

public field 와 #private field

클래스의 블럭 { } 내부 public field에서 바로 할당 = 한 변수는 인스턴스 객체의 프로퍼티로 호출 가능하다.

반면에 #을 붙여서 private field 에서 할당한 변수는 class 내부에서는 사용 가능하지만, 인스턴스 객체에서는 사용할 수 없다.

class User {
  #privateField = 1; // class 내부에서만 활용 가능한 데이터
  publicField = this.#privateField + 1; // 외부에서도 활용 가능
  /* #privateField는 호이스팅이 일어나지 않는다.
   선언하기 전 사용하면 TypeError: Cannot read private member #privateField from an object whose class did not declare it */
}

let user1 = new User();
console.log(user1.publicField); // 2
console.log(user1.privateField); // undefined

static

static 는 class 에만 지정되는 프로퍼티와 메서드이다.
instance object 에서는 호출할 수 없다.

class Account {
  constructor(balance) {
    this.balance = balance;
  }

  deposit() {
    this.balance++;
  }

  static owner = "ME";

  static printOwner() {
    console.log(Account.owner);
  }
}

const koreaBank = new Account(1000);
console.log(koreaBank); // Account { balance: 1000 }
console.log(koreaBank.__proto__); // 
console.log(koreaBank.owner); // undefined

console.log(Account.owner); // ME
Account.printOwner(); // ME

콘솔창으로 확인해보면(아래 사진) __proto__ 프로토타입 체인에 생성자 함수와 deposit()만 연결되어 있고, printOwner()는 연결되어 있지 않다.

instanceof

인스턴스 객체 instanceof 클래스
왼쪽의 객체가 오른쪽 클래스로 만들어진 인스턴스 객체가 맞다면 true, 아니면 false를 반환한다.
모든 객체는 Object 객체를 상속한다.

class Person { }

class User {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
}

const user1 = new User('Joy', 30);

console.log(user1 instanceof User); // true
console.log(user1 instanceof Person); // false
console.log('Joy' instanceof User); // false
console.log(User instanceof Object); // true
console.log(user1 instanceof Object); // true

command(또는 ctrl)을 누르고 정의된 classObject 를 누르면 정의되어 있는 내용을 볼 수 있다.

command 누르고 Object 클릭했을 때

MDN JavaScript Reference
유튜브 드림코딩 6. 클래스와 오브젝트의 차이점

profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글