JavaScript 객체 지향 프로그래밍(1)

설탕·2021년 12월 2일
0

객체란? 서로 연관된 변수와 함수를 그룹핑해서 이름을 붙인 것

객체 선언, 확인, 수정, 삭제

객체 선언

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 연산자

delete object.color;
delete object['color'];

console.log(object.color); // undefined

객체 반복문: for in

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

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

this: 자신이 속한 객체를 가리킴

const object = {
    num1: 3,
    num2: 5,
    sum: function() {
    	return this.num1 + this.num2;
    }
}
console.log(object.sum()); // 8
profile
공부 기록

0개의 댓글