JS - 객체

99·2024년 10월 25일

JS(자바스크립트)

목록 보기
2/11
post-thumbnail

JavaScript에서 객체는 키-값 쌍으로 이루어진 데이터 구조로, 데이터를 저장하고 관리하는 데 중요한 역할을 합니다.
객체는 여러 속성(프로퍼티)과 메서드를 가질 수 있으며, 함수와 배열 등 다양한 데이터 타입을 포함할 수 있습니다.



📌 객체 생성 방법


1. 객체 리터럴 방식

const person = {
	name : 'JJS',
    age : 45,
    greet : function(){
    	console.log('Hello, ' + this.name);
    }
};
const person = {};
person.name = 'JJS',
person.age = 45,
person.greete = function(){
	console.log('Hello, ' + this.name);
};
 

2. new Object() 사용

new 연산자를 통해 person 이란 객체를 만들고 person.name 이런식으로 객체에 접근하여 프로퍼티(속성)에 값을 넣어 주는 방식

const person = new Object();
person.name = 'JJS';
person.age = 45;
person.greet = function(){
	console.log('Hello, ' + this.name);
};

3. 생성자 함수 사용

function Person(name, age){
	this.name = name;
    this.age = age;
    this.greet = function(){
    	console.log('Hello, ' + this.name);
    };
}

const person = new Person('JJS', 45);

4. 클래스 사용(ES6)

class Person{
	constructor(name, age){
		this.name = name;
        this.age = age;
	}
    
    greet(){
    	console.log('Hello, ' + this.name);
    }
}

const person1 = new Person('JJS' , 45);


📌 객체의 구성요소

  • 프로퍼티(Property) : 객체가 가진 데이터(속성)입니다. 예를 들어 위의 예시 코드에서 쓰인nameageperson 객체의 프로퍼티 입니다.
  • 메서드(Method) : 객체가 가진 함수로, 특정 동작을 수행합니다. greetperson 객체의 메서드 입니다.


📌 객체의 활용법

객체의 프로퍼티 접근 및 수정

console.log(person.name); // 'JJS' 출력
console.log(person['age]); // 45 출력

person.age = 31; // age 프로퍼티 수정
person['name'] = 'Joon'; // name 프로퍼티 수정

객체의 프로퍼티 추가 및 삭제

person.job = 'Engineer'; // job 프로퍼티 추가
delete person.age; // age 프로퍼티 삭제


📌 객체의 메서드

객체 내 함수는 메서드라고 하며, this키워드를 사용하여 객체의 다른 프로퍼티에 접근할 수 있습니다.

const car = {
	brand : 'Toyota';
    start : function(){
    	console.log(this.brand + ' is starting')l
    }
};

car.start(); // 'Tyota is starting' 출력

객체의 주요 메서드

  • Object.key() : 객체의 모든 키를 배열로 반환합니다.
  • Object.values() : 객체의 모든 값을 배열로 반환합니다.
  • Object.entries() : 객체의 키-값 쌍을 배열로 반환합니다.
const person = {name : 'JJS', age : 43}

console.log(Object.key(person)); // ['name','age']
console.log(Object.values(person)); // ['JJS',43]
console.log(Object.entries(person)); // [['name','JJS'] ,['age',43]] 


마무리

JavaScript의 객체는 다양한 형태의 데이터를 관리하고 구조화하는 데 유용하며, 특히 사용자 정보, 설정 정보, 구성 데이터 등 연관데이터 그룹을 표현하는 데 적합합니다. 배열, 클래스, 함수와 결합하여 복잡한 데이터 구조를 표현할수도 있어 유연한 데이터 관리를 지원합니다.

profile
99

0개의 댓글