IT/HTML,CSS,JavaScript

[JavaScript] 자바스크립트 기초 복습 part7

j8970 2025. 3. 24. 16:39

자바스크립트 객체(Object) 기초 정리


📌 객체(Object)란?

객체는 관련된 데이터와 함수를 모아놓은 집합으로, 속성(프로퍼티)메서드(기능)로 구성됩니다.

  • 속성(Property): 객체가 가진 데이터 (예: 이름, 나이, 직업 등)
  • 메서드(Method): 객체가 수행할 수 있는 행동 (예: 걷다, 말하다 등)

🔹 객체지향 프로그래밍이란?

객체를 중심으로 프로그램을 구성하는 방식으로, 실세계의 모든 것을 객체로 표현하는 프로그래밍 패러다임입니다.


📌 객체 생성 및 멤버 접근

🔹객체 생성 방법

객체 리터럴 방식

let person = {
  name: "홍길동",
  age: 25,
  greet: function() {
    console.log("안녕하세요, " + this.name + "입니다.");
  }
};

생성자 함수 사용

function Human(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`안녕하세요, ${this.name}입니다.`);
  };
}

let person1 = new Human("김철수", 30);
person1.greet();

클래스 사용

class Human {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log(`안녕하세요, ${this.name}입니다.`);
  }
}

let person2 = new Human("이영희", 28);
person2.greet();

🔹 객체 멤버 접근 방법

1) 점 표기법: 객체명.속성명 또는 객체명.메서드명()
2) 대괄호 표기법: 객체명["속성명"]

console.log(person.name);  // 홍길동
console.log(person["age"]);  // 25

📌 this 키워드

this는 현재 실행 중인 코드가 속한 객체를 가리킵니다.

🔹 전역 컨텍스트에서의 this

console.log(this); // 브라우저 환경: window 객체, Node.js 환경: global 객체

🔹 객체 메서드에서의 this

let obj = {
  name: "객체",
  showThis: function() {
    console.log(this);
  }
};
obj.showThis();  // obj 객체 출력

🔹 화살표 함수에서의 this

화살표 함수는 this를 자신이 정의된 스코프에서 상속받습니다.

let objArrow = {
  name: "객체",
  showThis: () => {
    console.log(this);
  }
};
objArrow.showThis();  // 전역 객체 출력

📌 객체의 참조 타입

🔹 참조 복사 (얕은 복사)

객체를 변수에 할당하면 주소값이 복사됩니다.

let computer1 = { name: "삼성" };
let computer2 = computer1;
computer1.name = "애플";
console.log(computer2.name); // "애플"

🔹 깊은 복사

객체의 실제 값을 복사하여 독립적인 객체를 만듭니다.

let book1 = {
  title: "백설공주",
  author: "홍길동"
};
let book2 = JSON.parse(JSON.stringify(book1));
book2.title = "신데렐라";
console.log(book1.title); // "백설공주"
console.log(book2.title); // "신데렐라"

📌 객체 속성 확인 및 삭제

🔹 in 연산자

객체에 특정 속성이 존재하는지 확인합니다.

console.log("title" in book1);  // true
console.log("publisher" in book1);  // false

🔹 delete 연산자

객체의 속성을 삭제합니다.

delete book1.title;
console.log("title" in book1);  // false

🚀 객체 지향!!