Frontend

<Frontend> JavaScript / 객체(Object)

이게왜 2024. 3. 26. 16:42

Object

Object란?

  • 원시 타입(숫자, 문자열, boolean, null, undefined, Symbol)을 제외한 나머지 값들.
  • key와 value로 구성된 property(속성)의 집합
  • Object는 key와 value의 쌍으로 이루어진 container

그런 여기서 Property(속성)이 무엇인지 알아보겠습니다.

 

- Property

  • Property Name = key
  • Porpery value = value
let person = {
  name: "John",  // 'name'은 property name, "John"은 property value
  age: 30,       // 'age'는 property name, 30은 property value
  greet: function () { // 'greet'는 property name, function () { return "Hello, " + this.name; }은 property value
    return "Hello, " + this.name;
  }
};

console.log(person.name); // John
console.log(person.age); // 30
console.log(person.greet()); // Hello, John

 

이 코드로 예시를 들겠습니다.

person이라는 객체는 3개의 property를 가지고 있습니다.

  • Property Name : name, age, greet
  • Property Value : "John", 30, function() { return "Hello " + this.name }

 

- Method

JS에서는 Function과 Method를 구분하여야 합니다.

  • Method는 객체의 Property(속성)으로 저장된 함수이다.
  • Method는 특정 객체에 "속한" 함수로서, 그 객체를 통해 호출된다. 
let person = {
  name: "John",  // 'name'은 property name, "John"은 property value
  age: 30,       // 'age'는 property name, 30은 property value
  greet: function () { // 'greet'는 property name, function () { return "Hello, " + this.name; }은 property value
    return "Hello, " + this.name;
  }
};

console.log(person.name); // John
console.log(person.age); // 30
console.log(person.greet()); // Hello, John

 

위 코드에서 

greet: function () {
    return "Hello, " + this.name;
  },

 

부분은 person 객체의 property인 동시에 method입니다.


JS에서 객체 생성 방법

  • 객체 리터럴
  • 생성자 함수
  • 클래스

 

- 객체 리터럴

  • 간편한 문법
  • 동적 속성 추가 가능
  • {}를 사용해 객체를 만들고, property와 method를 정의
let person = {
  name: "John",
  age: 30,
  greet: function () {
    return "Hello, " + this.name;
  },
};

person.email = "hi@gmail.com"; //동적 property 추가
console.log(person.email);

 

 

- 생성자 함수

  • new 키워드 사용.
  • 객체를 여러 번 생성해야 하는 상황에서 유용.
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function () {
    return `Hello, ${this.name}`;
  };
}

const person1 = new Person("Jung", 30);
const person2 = new Person("Hun", 20);

console.log(person1.greet()); // Hello, Jung
console.log(person2.greet()); // Hello, Hun

 

 

- 클래스 사용

  • ES6+ 클래스 기반 문법 사용.
  • class 키워드를 사용하여 정의, 이후 new 키워드로 instance 생성.
  • 상속, 다형성(polymorphism) 사용 가능.
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet1() {
    return `Hello, ${this.name}`;
  }
}

let person = new Person("Jung", 30);
console.log(person.name); // Jung

class User extends Person {
  constructor(name, age, email) {
    super(name, age);
    this.email = email;
  }

  // greet1() {
  //   return `Hi, ${this.name}`;  Override
  // }

  greet2() {
    return `Hello, ${this.name}, ${this.email}`;
  }

  greet2(address) {
    return `Hello, ${this.name}, ${this.email}, ${address}`; // Overload
  }
}

let user = new User("Jung", 30, "hi@gmail.com");
console.log(user.greet1()); // Hello, Jung
// console.log(user.greet1());  Hi, Jung
console.log(user.greet2()); // Hello, Jung, hi@gmail.com
console.log(user.greet2("Seoul")); // Hello, Jung, Seoul

 

리터럴 vs 생성자 vs 클래스

생성방법 장점 단점 사용 시점
객체 리터럴  - 가장 간단하고 직관적
- 단일 객체 빠른 생성 및 초기화 가능
- 코드 중복 가능성
- 프토로타입 상속 설정 어려움
- 단순한 구조의 단일 객체가 필요 할 때
생성자 함수 - 유사 객체 여러 개 생성 가능  - 문법적으로 복잡하고 구식일 수 있음
- new 키워드 누락 시 버그 발생 가능
- 유사한 객체를 여러 개 생성해야 할 때
클래스 (ES6+) - 객체 지향 프로그래밍 지원
- 클래스 상속 간단 및 명확
- 구조적이고 명확한 문법 제공
- 이전 JS 버전에서 사용 어려움 - 객체 지향 프로그래밍 활용 시
- 큰 규모의 프로젝트나 팀 작업 시

 


Object 내에서 Method 표현

  • Object 내부에서 사용하는 Function은 Method이다.
  • Object의 property value.

 

- 리터럴로 객체 생성 시 선언 (Default)

const myObject = {
  property: "Value",
  myMethod: function () {
    console.log("This is a method.");
  },
};

myObject.myMethod(); // 출력: This is a method.
myObject.yourMethod = function () { // function(method) 동적 추가
  return "This is your method.";
};

console.log(myObject.yourMethod()); // 출력: This is your method.

 

 

- ES6 축약 메서드 표현법 (Shorten)

const myObject = {
  property: "Value",
  myMethod() {
    console.log("This is a method using ES6 shorthand.");
  },
};

myObject.myMethod(); // 출력: This is a method using ES6 shorthand.

 

- getter/setter, Private 변수

  • 외부 스코프에서 내부 스코프의 변수에 접근하지 못하도록 함.
  • 데이터의 안전한 관리가 목적이다.
  • 잘못된 참조 차단.
class Person {
  #name; // private 필드 선언

  constructor(name) {
    this.#name = name;
  }

  // getter
  getName() {
    return this.#name;
  }

  // setter
  setName(name) {
    this.#name = name;
  }
}

const person = new Person("John");
person.name = "Park"; // private 변수를 직접 변경했을 경우 반영되지 않음.
console.log(person.getName()); // John
person.setName("Jane");
console.log(person.getName()); // Jane