객체란? 서로 연관된 변수와 함수를 그룹핑해서 이름을 붙인 것
const object = {
name: 'lemon',
color: 'yellow',
taste: 'sour'
}
Property(속성): 'name: 'lemon'', 'color: 'yellow'', 'taste: 'sour''
Key(키): name, color, taste (따옴표 붙여도 되고 안 붙여도 됨)
Value(값): 'lemon', 'yellow', 'sour'
console.log(object.name); // lemon
console.log(object['name']; // lemon
object.name = 'banana';
object['taste'] = 'sweet';
delete object.color;
delete object['color'];
console.log(object.color); // undefined
for (const prop in object) {
console.log(prop, object[prop]); // key, value 출력
}
// name lemon
// color yellow
// taste sour
⚠ for in 안에서 value 불러올 때 prop는 변수이기 때문에
object[prop]
<< 이렇게 써야 함 (따옴표 없이)
object.prop
<< 이건 불가능
method
란? 객체에 속한 함수
const myMath = {
random: function() {
return Math.random();
},
floor: function(num) {
return Math.floor(num);
}
}
console.log(myMath.random()); // 0 이상 1 미만의 난수
console.log(myMath.floor(3.9)); // 3
this
: 자신이 속한 객체를 가리킴
const object = {
num1: 3,
num2: 5,
sum: function() {
return this.num1 + this.num2;
}
}
console.log(object.sum()); // 8