본문 바로가기

Front-End/JavaScript

JavaScript #10 (객체)

반응형

 

속성(property), 함수(method)를 함께 담을 수 있음.

 

{키(key) : 값(value} 쌍의 딕셔너리(dictionary) 형태로 표현.

 

const account = {
    userName: "홍길동",
    userAge: 30,
    userEmail: "hong@example.com"
};

 

객체의 속성을 직접 접근(객체["  "])해서 해당 속성의 값을 바로 호출할 수도 있다.

const product = {
    id: 101,
    name: "노트북",
    price: 1200000,
}

console.log(product["name"]);

 

 

 

예문 - 리터럴 방식 (*예를 들면 json 형식 파일에 담기는 내용 등등)

const user = {
    name: "철수",		// name 속성
    age: 20,			// age 속성
    greet: function () {    	// 객체 안에 함수도 들어갈 수 있음.
        alert("안녕하세요!");
    },
};
// 객체의 속성(key-value 쌍) 호출
console.log(user.name);		// user 객체에 있는 name 속성 호출
console.log(user.age);		// user 객체에 있는 age 속성 호출
user.greet();   		// 객체 안에 있는 함수 호출

 

 

실습

const user = {
name: "홍길동",
age: 100,
introduce: function () {
	alert(`안녕하세요! 저는 ${this.name}이고, ${this.age}살 입니다.`);
    },
};

 

 

실습 - 두 숫자를 입력받는 계산기

// 두 수를 입력받는 계산기
const calculator = {
    add : function (a, b) {
        return a + b;
    },
    subtract : function (a, b) {
        return a - b;
    },
    multiply : function (a, b) {
        return a * b;
    },
    divide : function (a, b) {
        return a / b;
    },
    remainder : function (a, b) {
        return a % b;
    }
}

console.log(calculator.add(3, 4))

- 7

 

 

 

심화 - for ~ in

const book = {};

book.title = "자바스크립트 입문";
book.author = "김작가";
book.year = 2025;

delete book.year;   // 속성값 제거

// 키:값 쌍에 각각 자동으로 지정
for (let key in book) {
    console.log(`${key}: ${book[key]}`);
}

 

※ 유사한 for of 문과의 차이는 아래 설명글 참고.

https://velog.io/@onea/JS-for-...of%EC%99%80-for-...in%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90

 

[JS] for ...of와 for ...in의 차이점

for문은 반복문이라는 것은 모두 다 알고 있으리라 믿는다. 아시다시피 for문은 이런식으로 사용할 수가 있겠다.사실 이 for문 하나로도 충분할 수 있겠다. 그러나 좀 더 우아하게 할 수 있는 게 없

velog.io

 

 

 

 

 

예문 - 생성자 함수 방식

// 생성자 함수
function Student(name, score) {
  this.name = name;
  this.score = score;
  this.sayHi = function () {
    alert(`안녕하세요! 저는 ${this.name}입니다.`);
  };
}

const s1 = new Student("영희", 90);
s1.sayHi(); 

- 안녕하세요! 저는 영희입니다.


// 객체 생성 (임의의 학생들 소환~~~)
const student1 = new Student("철수", 20, "남자", 2);
const student2 = new Student("유리", 18, "여자", 3);
const student3 = new Student("짱구", 17, "남자", 1);
const student4 = new Student("맹구", 22, "남자", 2);
const student5 = new Student("훈이", 18, "남자", 1);

student4.sayHi();

- 안녕하세요! 저는 맹구입니다.

※ 생성자 함수 Student에서 name과 score인자를 필요로 하는데,

이 때 this를 통해 각각의 객체를 식별할 수 있게끔 이름표를 붙인다는 느낌으로 이해하면 될 듯?

 

 

실습

// 생성자 함수를 이용해 Book 객체 여러 개 만들어보기
function Book(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

const book1 = new Book("책1", "저자1", 2025);
const book2 = new Book("책2", "저자2", 2024);
const book3 = new Book("책3", "저자3", 2023);

 

 

Date 객체 : 날짜와 시간 정보를 다루는 내장 객체

const now = new Date();		// Date 객체 생성

// getㅁㅁㅁㅁ로 현재 ㅁㅁㅁㅁ 정보를 가져올 수 있다.
console.log(now);			// 현재 시각
console.log(now.getFullYear());		// 연도
console.log(now.getMonth() + 1);	// 월 (0부터 시작)
console.log(now.getDate());		// 일

console.log(now.getDay());		// 요일 (0:일 ~ 6:토)
console.log(now.getHours());		// 시
console.log(now.getMinutes());		// 분
console.log(now.getSeconds());		// 초
console.log(now.getMilliseconds());	// 밀리초

 

 

예문 - 기념일 계산기 (생일, 태어난 날부터 ~ 오늘까지)

const today = new Date();
const birthday = new Date("1990-10-25");

let diff = today.getTime() - birthday.getTime();
let days = Math.floor(diff / (1000 * 60 * 60 * 24));

alert(`태어난 지 ${days}일이 지났습니다.`);

 

 

 

 

 

 

반응형