
다양한 타입의 값(원시 값 또는 다른 객체)를 하나의 단위로 구성한 복합적인 자료구조.
원시 값은 변경 불가능한 값 이지만 객체는 변경 가능한 값.
0개 이상의 프로퍼티로 구성된 집합이며, 프로퍼티는 키와 값으로 구성.
프로퍼티의 값이 함수일 경우, 일반 함수와 구분하기 위해 메서드라 부름.
const counter = {
num: 0, // 프로퍼티 -> key: value
increse: function () {
this.num++;
}
}
중괄호({...}) 내에 0개 이상의 프로퍼티를 정의
const person = {
name: 'Kim',
sayHello: function () {
console.log(`Hello! My name is ${this.name}.`);
}
};
console.log(typeof person); // object
console.log(person); // {name: "Kim", sayHello: ⨍}
const empty = {}; // 빈 객체
console.log(typeof empty); // object
,)로 구분.마침표 표기법, 대괄호 표기법이 존재.
const person = {
name: 'HyounSeok',
'last-name': 'Kim',
1: 10
};
// 마침표 표기법
person.name; // -> HyounSeok
// 대괄호 표기법
person['name']; // -> HyounSeok
// 존재하지 않는 프로퍼티
person.age; // -> undefined
// 식별자 네이밍 규칙을 따르지 않는 프로퍼티
person.'last-name'; // -> SyntaxError: Unexpected string
person.last-name; // -> 브라우저 환경: NaN
// -> Node.js 환경: last is not defined
person['last-name']; // -> Kim
// 프로퍼티 키가 숫자로 이루어진 문자열
person.1; // -> SyntaxError: Unexpected number
person.'1'; // -> SyntaxError: Unexpected string
person[1]; // -> 10
person['1']; // -> 10
이미 존재하는 프로퍼티 값을 할당하면 프로퍼티 값이 갱신 됨.
const person = {
name: 'Kim'
}
person.name = 'Lee';
console.log(person); // {name: "Lee"}
존재하지 않는 프로퍼티에 값을 할당하면 프로퍼티가 동적으로 생성되어 추가되고 프로퍼티 값이 할당 됨.
const person = {
name: 'Kim'
}
person.age = 20;
console.log(person); // {name: "Kim", age: 20}
delete 연산자를 사용.
존재하지 않는 프로퍼티를 삭제하면 아무 에러없이 무시 됨.
const person = {
name: 'Kim'
}
person.age = 20;
delete person.age;
delete person.address;
console.log(person); // {name: "Kim"}
JS의 함수는 객체(일급 객체)이므로 값으로 취급할 수 있기 때문에 프로퍼티 값으로 사용 가능.
프로퍼티 값이 함수일 경우 일반 함수와 구분하기 위해 메서드라 부름.
const circle = {
radius: 5,
getDiameter: function () {
return 2 * this.radius;
}
};
console.log(circle.getDiameter()); // 10