관련 데이터와 함수를 그룹화하는 컨테이너
속성(Properties)은 객체의 상태(state)를 나타낸다.
객체에 속성을 추가하거나 삭제하는 방법
// 속성 추가
person.job = "Developer";
// 속성 삭제
delete person.age;
객체의 속성을 호출하기 위한 방법
// 점 표기법(dot notation)
****console.log(person.firstName);
// 대괄호 표기법(bracket notation)
console.log(person["lastName"]);
console.log(person["middle-name"]);
메서드(Methods)는 객체의 동작(behavior)을 구현한다.
// 기존 함수 표기법: 객체 내부에서 속성을 선언할 때와 같이 선언
getName: function () {
return this.name;
},
// ES6 함수 표기법: 객체 외부에서 함수를 선언할 때와 같이 선언
getName() {
return this.name;
},
// 메서드 호출
person.greet(); // "Hello, John"
객체는 두 가지 방법으로 생성할 수 있다. 리터럴 방식과, 생성자 함수 방식이다.
// 1. 리터럴 방식: const obj1 = {};
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log("Hello, " + this.firstName);
}
};
// 2. 생성자 함수 사용: const obj2 = new Object();
const anotherPerson = new Object();
anotherPerson.firstName = "Jane";
anotherPerson.lastName = "Doe";
1. 리터럴 방식이 더 자주 사용된다.객체 참조 변수는 객체의 메모리 주소를 담고 있는 변수이다. 위의 예에서
person은 배열 객체의 참조 변수이며, 호출 시 메모리 주소를 반환한다.
객체의 메서드를 연속적으로 호출하는 것을 메서드 체이닝이라고 한다. 메서드 체이닝 기법을 통해 코드의 가독성을 향상시키고, 작업의 연속성을 명확히 할 수 있다.
객체 내에서 현재 객체를 가리키는 키워드이다. 메서드 내부에서
this를 사용하면, 해당 메서드를 호출한 객체에 접근할 수 있습니다.
객체 내에 특정 속성이 존재하는지 확인한다.
const person = {
name: "홍길동",
age: 30
};
console.log("name" in person); // true
console.log("address" in person); // false객체가 null이거나 undefined인 경우를 처리한다. TypeError가 발생하는 것을 방지한다.
const person = {
name: "홍길동",
contact: {
email: "hong@example.com"
}
};
console.log(person.contact.email); // "hong@example.com"
console.log(person.contact.phone?.number); // undefined피연산자 중 하나가 null이나 undefined가 아니면 그 값을 반환한다.
const input = null;
const defaultValue = "기본값";
const value = input ?? defaultValue;
console.log(value); // "기본값"