웹개발/JavaScript

10 - 1. JS 객체 정의 및 사용

lukeit 2024. 10. 8. 13:42

객체 = 필드 + 메서드 (프로퍼티의 집합)

  • 요소 (Element = 객체) = 속성 + 프로퍼티(Attributes)의 집합
    • 요소: <head></head>
    • 속성: <div class=”…”>

메서드

  1. Default 버전으로 표현
    function() { } 을 사용한다.
var person = {
    name: "Aaron",
    sayName: function() {
        console.log(this.name);
    }
};

class Person {
    name = "Aaron";
    sayName = function() {
        console.log(this.name);
    }
};
  1. Shorten 버전으로 표현
var person = {
    name: "Aaron",
    sayName() {
        console.log(this.name);
    }
};

JS 객체 생성 방법

  • Java처럼 객체 사용에 꼭 Class가 필요한 건 아니다.
    • 일반적으로 Class 없이 Method + Field로만 모든 것을 만들 수 있다.
    • 하지만 디자인 패턴 같은 객체지향적 요인으로 코드 재사용성을 증대시키기 위해 Class를 사용한다.
      • Class를 생성하는 이유: Encapsulation 때문
      • 필드를 최대한 감추고, 최소한의 메서드만 노출하기 위함.
      • Object Oriented Programming (OOP)를 잘하는 기준은 클래스 (독립된 시스템 구축)를 얼마나 잘 만드는가?
      • 즉, "독립"의 영역을 얼마나 잘 구분하는가?
class User {
    // 1. 필드 생성
    // #을 붙이면 private field로 바뀐다.
    // last_name과 #last_name은 다른 field로 취급된다.
    // 메서드를 생성할 때도 #를 붙여 private을 사용한다고 명시해주어야 한다.
    #first_name;
    #last_name;

    // 2. 생성자 생성
    constructor(first_name, last_name) {
        this.#first_name = first_name;
        this.#last_name = last_name;
    }

    // 3. Method 생성
    #fullname() {
        return `${this.#first_name} ${this.#last_name}`;
    }

    // public method
    information() {
        console.log(`${this.#fullname()} - 사람이름`);
    }

    // getter 만들기
    // getter는 항상 무언가를 반환해야 한다
    get first_name() {
        return this.#first_name;
    }

    // setter 만들기
    set last_name(parameter) {
        this.#last_name = parameter;
    }
}

// 사용해보기

var hello = new User("Luke", "Seo");

// field를 가져올 수 있지만 지금은 전부 #로 막혀있어 가져오는 게 없다
Object.getOwnPropertyNames(hello);         // []
// setter를 이용해서 last_name을 바꿔줬다
hello.last_name = "Kim";
// 바꾸었지만 last_name은 private이기에 이런식으로 접근이 불가능하다
console.log(hello.last_name);              // undefined
// 그래서 public method인 'information'을 사용해 접근만 가능하다
hello.information();                       // "Luke Kim - 사람이름"
반응형