[JS] Js기초 객체

javaScript 기초를 탄탄하게 다져보자

Posted by lim.Chuck on December 6, 2024

[JavaScript]

기초

  1. [JS] Js기초
  2. [JS] Js기초 변수
  3. [JS] Js기초 자료형
  4. [JS] Js기초 형변환
  5. [JS] Js기초 연산자
  6. [JS] Js기초 반복문
  7. [JS] Js기초 switch
  8. [JS] Js기초 function
  9. [JS] Js기초 객체
  10. [JS] Js기초 배열

중급

  1. [JS] Js중급 호이스팅(Hoisting)과 TDZ(Temporal Dead Zone)
  2. [JS] Js중급 생성자함수
  3. [JS] 객체 메소드(Object methods), 계산된 프로퍼티(Computed property)
  4. [JS] 심볼(Symbol)
  5. [JS] WeakMap WeakSet
  6. [JS] 숫자, 수학 method (Number, Math)
  7. [JS] 문자열 메소드(String methods)
  8. [JS] 배열 메소드(Array methods)
  9. [JS] 구조 분해 할당 (Destructuring assignment)
  10. [JS] 매개변수 리스트와 전개 문법(Rest parameters and spread syntax)
  11. [JS] 클로저(Closure)
  12. [JS] setTimeout / setInterval
  13. [JS] call / apply / bind
  14. [JS] 상속, 프로토타입(Prototype)
  15. [JS] 클래스(Class)
  16. [JS] 클로미스(Promise)
  17. [JS] 비동기 처리(Async/Await)
  18. [JS] Generator
  19. [JS] 메모리 릭(Memory Leak)

객체(Object)를 배워보자! 진짜 실생활에서 쓸 수 있는 꿀팁이야! 🍯

1. 객체 만들기 (기본)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 기본적인 객체 생성
let dog = {
  name: "멍멍이",
  age: 3,
  breed: "골든리트리버",
  bark: function () {
    console.log("왈왈! 🐕");
  },
  // 메서드 단축 구문
  sleep() {
    console.log("쿨쿨... 😴");
  },
};

// 객체 사용하기
console.log(dog.name); // "멍멍이"
console.log(dog["age"]); // 3
dog.bark(); // "왈왈! 🐕"
dog.sleep(); // "쿨쿨... 😴"

2. 객체 속성 다루기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 속성 추가하기
let cat = {
  name: "냥이",
};

cat.age = 2; // 새로운 속성 추가
cat["color"] = "검정"; // 대괄호로도 추가 가능!

// 속성 삭제하기
delete cat.age;

// 속성 존재 확인
console.log("name" in cat); // true
console.log("age" in cat); // false

// 객체 복사하기 (얕은 복사)
let copyCat = { ...cat }; // 스프레드 연산자 사용

3. 객체 메서드와 this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let player = {
  name: "게임마스터",
  hp: 100,
  mp: 50,

  // this로 자기 자신의 속성 접근
  status() {
    console.log(`
            이름: ${this.name}
            HP: ${this.hp}
            MP: ${this.mp}
        `);
  },

  attack(target) {
    console.log(`${this.name}이(가) ${target}을 공격! ⚔️`);
    this.mp -= 10;
  },
};

player.status();
player.attack("슬라임");

4. 객체 생성자 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 생성자 함수 (대문자로 시작!)
function Character(name, type) {
  this.name = name;
  this.type = type;
  this.level = 1;
  this.hp = 100;

  this.levelUp = function () {
    this.level++;
    this.hp += 20;
    console.log(`${this.name} 레벨업! 🎉 (현재 레벨: ${this.level})`);
  };
}

// 새로운 캐릭터 만들기
let warrior = new Character("전사왕", "전사");
let mage = new Character("마법사왕", "마법사");

warrior.levelUp(); // "전사왕 레벨업! 🎉 (현재 레벨: 2)"

5. 클래스로 객체 만들기 (모던 방식! 😎)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Pet {
  constructor(name, type) {
    this.name = name;
    this.type = type;
    this.hunger = 100;
  }

  feed() {
    this.hunger = 100;
    console.log(`${this.name}이(가) 배부르다! 😋`);
  }

  play() {
    this.hunger -= 30;
    console.log(`${this.name}이(가) 신나게 놀았다! 🎾`);

    if (this.hunger < 30) {
      console.log(`${this.name}이(가) 배고파 보인다... 🥺`);
    }
  }
}

let myPet = new Pet("몽실이", "강아지");
myPet.play();
myPet.play();
myPet.feed();

6. 실전 예제: 게임 아이템 시스템!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Item {
  constructor(name, type, price) {
    this.name = name;
    this.type = type;
    this.price = price;
  }
}

class Inventory {
  constructor() {
    this.items = [];
    this.gold = 1000;
  }

  addItem(item) {
    this.items.push(item);
    console.log(`${item.name} 획득! 🎁`);
  }

  buyItem(item) {
    if (this.gold >= item.price) {
      this.gold -= item.price;
      this.addItem(item);
      console.log(`구매 완료! 남은 골드: ${this.gold} 💰`);
    } else {
      console.log("골드가 부족해요... 😢");
    }
  }

  showItems() {
    console.log("✨ 인벤토리 ✨");
    this.items.forEach((item) => {
      console.log(`- ${item.name} (${item.type})`);
    });
  }
}

// 사용 예시
let sword = new Item("불꽃검", "무기", 500);
let potion = new Item("힐링포션", "소비", 100);

let myInventory = new Inventory();
myInventory.buyItem(sword);
myInventory.buyItem(potion);
myInventory.showItems();

꿀팁! 🍯

  1. 구조 분해 할당
1
2
3
4
5
6
7
8
9
const hero = {
  name: "슈퍼맨",
  power: "초강력",
  fly: true,
};

// 이렇게 쉽게 변수로 뽑아낼 수 있어!
const { name, power } = hero;
console.log(name); // "슈퍼맨"
  1. 객체 합치기
1
2
3
4
5
6
const basic = { hp: 100, mp: 50 };
const skills = { fireball: "🔥", heal: "💚" };

// 두 객체 합치기
const character = { ...basic, ...skills };
console.log(character); // { hp: 100, mp: 50, fireball: "🔥", heal: "💚" }

이제 객체는 마스터했다! 진짜 실용적이지 않아? 😎