클래스 레벨, 인스턴스 레벨

Tags
class
instance
부가 설명
비고

1) Objective-C 클래스 도식도

objective-c 공부할 때 봤던 클래스 도식도가 이해에 도움이 많이 되었기에 같이 둠.
  • 클래스 자체도 오브젝트로 존재한다. (이미 만들어져서 존재함)
    • ⇒ new 키워드로 생성자 함수 호출, 클래스 메소드 호출, 클래스 멤버 변수 접근이 가능한 이유
notion image
 

2) 클래스 레벨

💡
- 객체와 상관없이 항상 동일한 값을 갖는 멤버변수 - 멤버변수를 참조하지 않는 메소드
  • 멤버변수와 멤버함수 앞에 static 키워드를 붙이면 클래스 레벨로 동작.
    • 생성한 객체에는 할당되지 않고, 클래스 오브젝트에만 존재함.
  • 참조는 클래스명.변수명, 클래스명.함수명(인자) 이런식으로 접근 가능.
class calc { // 객체별로 다른 값을 가질 필요가 없는 변수는 클래스 레벨로 둔다. static writer: string = "night-ohl"; // 객체의 멤버변수 값을 참조하지 않는 함수는 클래스 레벨로 둔다. static add(num1: number, num2: number): number { return num1 + num2; } // 객체의 멤버변수 값을 참조하지 않는 함수는 클래스 레벨로 둔다. static sub(num1: number, num2: number): number { return num1 - num2; } } console.log(`1 + 2 : ${calc.add(1, 2)}`); // "클래스명." 으로 바로 접근 console.log(`class writer : ${calc.writer}`); // "클래스명." 으로 바로 접근
notion image

3) 인스턴스 레벨

💡
- 객체별로 값이 달라질 수 있는 멤버변수 - 객체의 멤버변수를 참조하는 멤버함수
  • 그냥 일반적으로 선언하면 오브젝트 레벨로 동작함.
  • 객체 생성 시 객체 내부에 할당되며, 객체별로 할당되므로 객체별로 서로 다른 값을 가질 수 있다.
class Cat { weight: number; age: number; name: string; hungry: number; constructor(weight: number, age: number, name: string) { this.weight = weight; this.age = age; this.name = name; this.hungry = 30; // 공복은 default로 30으로 줌. } feed(feed: number) { this.hungry += feed; } } const myCat = new Cat(5, 2, "깜이"); myCat.feed(20); console.log(myCat); const myCat2 = new Cat(3, 1, "깜둥이"); console.log(myCat2);
notion image