1. 자바스크립트 객체: 기본 개념과 활용
1.1 객체란 무엇인가?
자바스크립트에서 객체(Object) 는 키(key)와 값(value) 쌍으로 이루어진 데이터의 집합입니다. 마치 사물함에 이름표(key)를 붙이고 그 안에 물건(value)을 보관하는 것과 비슷합니다.
- 키(key): 속성(property)의 이름으로, 문자열만 사용할 수 있습니다.
- 값(value): 해당 속성에 저장되는 데이터로, 숫자, 문자열, 불리언, 배열, 함수 등 어떤 타입의 값이든 될 수 있습니다.
1.2 객체 생성 및 활용 예제
객체를 만드는 가장 간단한 방법은 객체 리터럴(Object Literal) 표기법을 사용하는 것입니다.
// person 객체 생성
let person = {
name: "홍길동", // 문자열 속성
age: 30, // 숫자 속성
isStudent: false, // 불리언 속성
hobbies: ["독서", "게임"], // 배열 속성
greet: function() { // 함수(메서드) 속성
// this는 현재 객체(person)를 가리킵니다.
console.log("안녕하세요, 제 이름은 " + this.name + "입니다.");
}
};
// address 객체 추가 예제
let address = {
street: "123 Main St",
city: "Anytown",
zipCode: "12345"
};
// 객체 안에 객체를 속성으로 추가
person.address = address;
// 객체의 속성으로 배열을 사용하고, 배열의 요소로 객체를 추가
person.family = [
{ name: "김부모", relation: "아버지" },
{ name: "이부모", relation: "어머니" }
];
2. 객체의 속성(Property) 다루기
2.1 속성 접근 및 수정: 점 표기법 (Dot Notation)
객체 이름 뒤에 점(.
)을 붙이고 속성 이름을 적어 속성에 접근하거나 수정할 수 있습니다.
console.log(person.name); // 출력: 홍길동
console.log(person.age); // 출력: 30
person.age = 31; // 나이 수정
console.log(person.age); // 출력: 31
person.greet(); // 출력: 안녕하세요, 제 이름은 홍길동입니다.
// 중첩된 객체의 속성에 접근
console.log(person.address.city); // 출력: Anytown
// 배열 속성의 요소에 접근
console.log(person.family[0].name); // 출력: 김부모
2.2 속성 접근 및 수정: 대괄호 표기법 (Bracket Notation)
객체 이름 뒤에 대괄호([]
)를 붙이고 속성 이름을 문자열 형태로 적어 속성에 접근하거나 수정할 수 있습니다.
console.log(person["name"]); // 출력: 홍길동
console.log(person["isStudent"]); // 출력: false
person["name"] = "이순신"; // 이름 변경
console.log(person["name"]); // 출력: 이순신
// 변수를 사용하여 속성에 접근
let propertyName = "hobbies";
console.log(person[propertyName]); // 출력: ["독서", "게임"]
// 동적으로 속성 이름 생성 및 접근
let newProperty = "phoneNumber";
person[newProperty] = "010-1234-5678";
console.log(person.phoneNumber); // 출력: 010-1234-5678
// 계산된 속성명 (Computed Property Names) 사용 (ES6 기능)
const prefix = "user";
const user = {
[`${prefix}Name`]: "김코딩",
[`${prefix}Age`]: 28,
};
console.log(user.userName); // 출력: 김코딩
3. 객체의 메서드 (Method)
3.1 메서드란 무엇인가?
객체의 속성 중 함수인 것을 메서드(Method) 라고 부릅니다. 메서드는 객체와 관련된 동작을 정의합니다.
3.2 메서드 정의 및 호출 예제
let calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // 출력: 8
console.log(calculator.subtract(10, 4)); // 출력: 6
// 객체에 새로운 메서드 추가
calculator.multiply = function(a, b) {
return a * b;
};
console.log(calculator.multiply(2, 6)); // 출력: 12
// ES6의 간결한 메서드 구문 사용
const mathUtils = {
cube(x) {
return x * x * x;
},
square(x) {
return x * x;
}
};
console.log(mathUtils.cube(3)); // 출력: 27
4. 자바스크립트 내장 객체 (Built-in Objects)
4.1 내장 객체 소개
자바스크립트는 효율적인 프로그래밍을 위해 다양한 내장 객체를 제공합니다. 내장 객체는 이미 정의되어 있어 별도의 생성 과정 없이 바로 사용할 수 있습니다.
내장 객체 | 설명 |
---|---|
Object |
모든 자바스크립트 객체의 기본이 되는 객체 |
Array |
배열을 다루기 위한 객체 |
String |
문자열을 다루기 위한 객체 |
Number |
숫자를 다루기 위한 객체 |
Boolean |
불리언 값을 다루기 위한 객체 |
Math |
수학적 연산을 위한 객체 |
Date |
날짜와 시간을 다루기 위한 객체 |
Function |
함수를 다루기 위한 객체. 함수도 객체의 특별한 형태입니다. |
4.2 Math
객체 활용 예제
Math
객체는 수학적 계산에 유용한 메서드들을 제공합니다.
// 최댓값 찾기
let maxNumber = Math.max(10, 5, 25, 8);
console.log(maxNumber); // 출력: 25
// 난수 생성 (0 이상 1 미만의 난수)
let randomNumber = Math.random();
console.log(randomNumber);
// 반올림
let roundedNumber = Math.round(3.6);
console.log(roundedNumber); // 출력: 4
// 소수점 이하 버림
let floorNumber = Math.floor(5.9);
console.log(floorNumber); // 출력: 5
// 소수점 이하 올림
let ceilNumber = Math.ceil(2.1);
console.log(ceilNumber); // 출력: 3
4.3 Date
객체 활용 예제
Date
객체는 날짜와 시간을 다룰 때 사용합니다.
// 현재 날짜와 시간을 나타내는 Date 객체 생성
let today = new Date();
console.log(today); // 현재 날짜와 시간 출력 (예: 2023-10-27T03:50:00.000Z)
// 특정 날짜와 시간을 나타내는 Date 객체 생성
let specificDate = new Date(2023, 9, 27); // 월은 0부터 시작 (9는 10월)
console.log(specificDate); // 출력: 2023-10-26T15:00:00.000Z (시간대는 다를 수 있음)
// 날짜 정보 얻기
console.log(today.getFullYear()); // 년도 출력
console.log(today.getMonth()); // 월 출력 (0부터 시작)
console.log(today.getDate()); // 일 출력
console.log(today.getDay()); // 요일 출력 (0: 일요일, 1: 월요일, ...)
console.log(today.toLocaleDateString()); // 현재 날짜 형식으로 출력 예시 : '2023/10/03'
// 시간 정보 얻기
console.log(today.getHours()); // 시 출력
console.log(today.getMinutes()); // 분 출력
console.log(today.getSeconds()); // 초 출력
// 특정 날짜의 타임스탬프 얻기
let timestamp = specificDate.getTime();
console.log(timestamp); // 출력: 1970년 1월 1일 00:00:00 UTC로부터 경과한 밀리초
4.4 String
객체 활용 예제
String
객체는 문자열 처리에 유용한 메서드들을 제공합니다.
let message = "Hello, World!";
console.log(message.length); // 문자열 길이 출력: 13
console.log(message.toUpperCase()); // 대문자로 변환: HELLO, WORLD!
console.log(message.toLowerCase()); // 소문자로 변환: hello, world!
console.log(message.indexOf("World")); // 부분 문자열 위치 찾기: 7
console.log(message.slice(0, 5)); // 문자열 자르기: Hello
// 문자열에서 특정 문자 개수 세기
let count = (message.match(/l/g) || []).length;
console.log(count); // 출력: 3
// 문자열 바꾸기 (replace)
let newMessage = message.replace("World", "JavaScript");
console.log(newMessage); // 출력: Hello, JavaScript!
// 문자열 양쪽 공백 제거 (trim)
let spacedString = " trim me ";
console.log(spacedString.trim()); // 출력: trim me
4.5 Array
객체 활용 예제
Array
객체는 배열을 다루는데 유용한 메서드들을 제공합니다.
let fruits = ["사과", "바나나", "오렌지"];
console.log(fruits.length); // 배열 길이 출력: 3
console.log(fruits[0]); // 첫 번째 요소 접근: 사과
fruits.push("포도"); // 배열 끝에 요소 추가
console.log(fruits); // 출력: ["사과", "바나나", "오렌지", "포도"]
fruits.pop(); // 배열 끝에서 요소 제거
console.log(fruits); // 출력: ["사과", "바나나", "오렌지"]
fruits.unshift("딸기"); // 배열 앞에 요소 추가
console.log(fruits); // 출력: ["딸기", "사과", "바나나", "오렌지"]
fruits.shift(); // 배열 앞에서 요소 제거
console.log(fruits); // 출력: ["사과", "바나나", "오렌지"]
// 배열의 모든 요소에 대해 함수 실행 (forEach)
fruits.forEach(function(fruit) {
console.log("과일: " + fruit);
});
// 배열의 각 요소를 변환 (map)
let upperCaseFruits = fruits.map(function(fruit) {
return fruit.toUpperCase();
});
console.log(upperCaseFruits); // 출력: ["사과", "바나나", "오렌지"]
// 배열에서 특정 조건에 맞는 요소만 추출 (filter)
let longNameFruits = fruits.filter(function(fruit) {
return fruit.length > 2;
});
console.log(longNameFruits); // 출력: ["바나나", "오렌지"]
4.6 Number
객체 활용 예제
Number
객체는 숫자 처리에 유용한 메서드를 제공합니다.
let num = 123.456;
console.log(num.toFixed(2)); // 소수점 둘째 자리까지 반올림: 123.46
console.log(num.toPrecision(3)); // 유효 숫자 3자리까지 표시: 123
console.log(Number.parseInt("123")); // 문자열을 정수로 변환: 123
console.log(Number.parseFloat("3.14")); // 문자열을 실수로 변환: 3.14
// 숫자가 정수인지 확인 (isInteger)
console.log(Number.isInteger(10)); // 출력: true
console.log(Number.isInteger(10.5)); // 출력: false
// 숫자가 NaN(Not a Number)인지 확인 (isNaN)
console.log(Number.isNaN(NaN)); // 출력: true
console.log(Number.isNaN(10)); // 출력: false
4.7 Boolean
객체 활용 예제
Boolean
객체는 참(true
) 또는 거짓(false
) 값을 나타내는 불리언 값을 다룹니다.
let isTrue = true;
let isFalse = false;
console.log(isTrue); // 출력: true
console.log(isFalse); // 출력: false
// Boolean 객체는 조건문에서 유용하게 사용됩니다.
if (isTrue) {
console.log("This will be executed.");
}
if (!isFalse) {
console.log("This will also be executed.");
}
// Boolean() 함수를 사용하여 다른 타입의 값을 불리언으로 변환
console.log(Boolean(0)); // 출력: false
console.log(Boolean("")); // 출력: false
console.log(Boolean(null)); // 출력: false
console.log(Boolean(undefined)); // 출력: false
console.log(Boolean(1)); // 출력: true
console.log(Boolean("hello")); // 출력: true
console.log(Boolean({})); // 출력: true
4.8 Function
객체 활용 예제
Function
객체는 함수를 나타내며, 함수를 동적으로 생성하거나 함수에 대한 정보를 얻는 데 사용됩니다.
// 함수 선언
function add(a, b) {
return a + b;
}
// Function 객체를 사용하여 함수 생성
const multiply = new Function("a", "b", "return a * b");
console.log(add(2, 3)); // 출력: 5
console.log(multiply(4, 5)); // 출력: 20
// 함수는 객체이므로 속성을 가질 수 있습니다.
add.description = "두 수를 더하는 함수";
console.log(add.description); // 출력: 두 수를 더하는 함수
// arguments 객체를 사용하여 함수에 전달된 인자의 개수 확인
function getArgCount() {
return arguments.length;
}
console.log(getArgCount(1, 2, 3, 4)); // 출력: 4
// call() 메서드를 사용하여 함수 호출 시 this 값 지정
function greet(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
const person3 = { name: "김철수" };
greet.call(person3, "안녕"); // 출력: 안녕, 김철수!
5. 사용자 정의 객체 (Custom Objects)
5.1 사용자 정의 객체 생성
내장 객체 외에도 필요에 따라 직접 객체를 정의하여 사용할 수 있습니다. 이를 사용자 정의 객체라고 합니다. 사용자 정의 객체를 생성하는 방법에는 크게 두 가지가 있습니다.
5.1.1 객체 리터럴 방식
const person = {
name: "홍길동",
age: 30,
greet: function() {
console.log(`안녕하세요, 제 이름은 ${this.name} 입니다.`);
}
};
person.greet(); // 출력: 안녕하세요, 제 이름은 홍길동 입니다.
// 객체 리터럴 방식으로 book 객체 생성
const book = {
title: "자바스크립트 완벽 가이드",
author: "데이비드 플래너건",
pages: 1000,
getInfo: function() {
return `${this.title}, 저자: ${this.author}, ${this.pages} 페이지`;
}
};
console.log(book.getInfo()); // 출력: 자바스크립트 완벽 가이드, 저자: 데이비드 플래너건, 1000 페이지
5.1.2 생성자 함수 (Constructor Function) 방식
생성자 함수는 new
키워드와 함께 호출되어 객체를 생성하는 함수입니다. 생성자 함수를 사용하면 동일한 구조의 객체를 여러 개 만들 때 유용합니다. 관례적으로 생성자 함수의 이름은 대문자로 시작합니다.
function Person(name, age) {
// this는 생성될 객체를 가리킵니다.
this.name = name;
this.age = age;
this.greet = function() {
console.log(`안녕하세요, 제 이름은 ${this.name} 입니다.`);
};
}
// new 키워드를 사용하여 Person 객체 생성
const person1 = new Person("김철수", 25);
const person2 = new Person("이영희", 28);
person1.greet(); // 출력: 안녕하세요, 제 이름은 김철수 입니다.
person2.greet(); // 출력: 안녕하세요, 제 이름은 이영희 입니다.
// 생성자 함수 방식으로 Product 객체 생성
function Product(name, price) {
this.name = name;
this.price = price;
this.displayPrice = function() {
console.log(`${this.name}의 가격은 ${this.price}원 입니다.`);
};
}
const product1 = new Product("노트북", 1000000);
const product2 = new Product("마우스", 20000);
product1.displayPrice(); // 출력: 노트북의 가격은 1000000원 입니다.
product2.displayPrice(); // 출력: 마우스의 가격은 20000원 입니다.
5.2 사용자 정의 객체에 속성 및 메서드 추가
const car = {
brand: "현대",
model: "아반떼",
year: 2020
};
// 속성 추가
car.color = "흰색";
// 메서드 추가
car.getCarInfo = function() {
return `${this.brand} ${this.model}, 연식:${this.year}, 색상: ${this.color}`;
};
console.log(car.getCarInfo()); // 출력: 현대 아반떼, 연식:2020, 색상: 흰색
// car 객체에 시동 거는 메서드 추가
car.startEngine = function() {
console.log(`${this.model} 시동을 걸었습니다.`);
};
car.startEngine(); // 출력: 아반떼 시동을 걸었습니다.
// car 객체에 주행 거리 속성 추가 및 주행 메서드 추가
car.mileage = 0;
car.drive = function(distance) {
this.mileage += distance;
console.log(`${distance}km 주행했습니다. 총 주행 거리: ${this.mileage}km`);
};
car.drive(100); // 출력: 100km 주행했습니다. 총 주행 거리: 100km
car.drive(50); // 출력: 50km 주행했습니다. 총 주행 거리: 150km
5.3 프로토타입을 이용한 상속 (Inheritance)
자바스크립트는 프로토타입 기반 상속을 지원합니다. 프로토타입을 사용하면 객체 간에 속성과 메서드를 상속하여 코드 재사용성을 높일 수 있습니다.
// 부모 생성자 함수
function Vehicle(brand) {
this.brand = brand;
}
// 부모 객체의 프로토타입에 메서드 추가
Vehicle.prototype.getBrand = function() {
return this.brand;
};
// 자식 생성자 함수
function Car(brand, model) {
// Vehicle 생성자 함수를 호출하여 brand 속성 초기화
Vehicle.call(this, brand);
this.model = model;
}
// Car의 프로토타입을 Vehicle의 프로토타입으로 설정하여 상속 관계 형성
Car.prototype = Object.create(Vehicle.prototype);
// Car의 생성자 함수를 다시 Car로 설정
Car.prototype.constructor = Car;
// Car 객체의 프로토타입에 메서드 추가
Car.prototype.getModel = function() {
return this.model;
};
// Car 객체 생성
const myCar = new Car("BMW", "X5");
// 상속받은 메서드 사용
console.log(myCar.getBrand()); // 출력: BMW
console.log(myCar.getModel()); // 출력: X5
// Vehicle 객체의 프로토타입에 displayInfo 메서드 추가
Vehicle.prototype.displayInfo = function() {
console.log(`브랜드: ${this.getBrand()}`);
};
// Car 객체의 프로토타입에 displayInfo 메서드 오버라이딩 (재정의)
Car.prototype.displayInfo = function() {
console.log(`브랜드: ${this.getBrand()}, 모델: ${this.getModel()}`);
};
// 상속받은 displayInfo 메서드 사용
myCar.displayInfo(); // 출력: 브랜드: BMW, 모델: X5
// ElectricCar 생성자 함수를 Car로부터 상속
function ElectricCar(brand, model, batteryCapacity) {
Car.call(this, brand, model); // 부모 생성자 호출
this.batteryCapacity = batteryCapacity;
}
ElectricCar.prototype = Object.create(Car.prototype);
ElectricCar.prototype.constructor = ElectricCar;
ElectricCar.prototype.getBatteryInfo = function() {
console.log(`배터리 용량: ${this.batteryCapacity}kWh`);
};
const myElectricCar = new ElectricCar("Tesla", "Model S", 100);
myElectricCar.displayInfo(); // 출력: 브랜드: Tesla, 모델: Model S
myElectricCar.getBatteryInfo(); // 출력: 배터리 용량: 100kWh
6. 결론
지금까지 자바스크립트 객체의 기본 개념, 내장 객체, 사용자 정의 객체에 대해 자세히 살펴보았습니다. 각 섹션별로 예제를 풍부하게 추가하여 이해를 돕고, 명확한 대제목과 부제목을 사용하여 가독성을 높였습니다. 객체는 자바스크립트 프로그래밍의 핵심 요소이며, 데이터를 효율적으로 관리하고 기능을 조직화하는 데 필수적입니다. 이 글에서 배운 내용을 바탕으로 객체를 능숙하게 활용하여 더욱 강력하고 유연한 자바스크립트 프로그램을 작성하시길 바랍니다.
'프로그래밍 > Javascript' 카테고리의 다른 글
DOM (Document Object Model): 웹 페이지의 구조와 상호작용을 위한 모든 것 (0) | 2025.02.11 |
---|---|
자바스크립트 배열 정복: 개념부터 다차원 배열, 유용한 메소드까지 총정리! (0) | 2025.02.10 |
자바스크립트 함수 완전 정복: 표현식, 클로저, 콜백까지 파헤치기 (0) | 2025.02.10 |
자바스크립트 기본 정복: 변수부터 함수까지, 핵심 가이드 (0) | 2025.02.10 |
자바스크립트: 웹 세상을 움직이는 마법의 언어 (0) | 2025.02.10 |