사용자 정의 객체를 정의하는 방법은 리터럴 객체 형태와 new 연산자를 사용한 객체 정의, 그리고 생성자 함수, class를 이용하는 형태로 구분된다.
리터럴 객체 정의
가장 쉬운 객체 정의 방법이다. 이 방법을 사용하면 하나의 명령문에 객체를 정의하고 만들 수 있다. 리터럴 객체를 정의하면 객체는 변수처럼 사용되며, 속성과 메서드가 객체에 바로 할당되면서 객체가 생성된다.
let 객체 이름 = {
객체 속성키 : 속성값,
...,
객체 메서드명 : function() {
함수구문;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let star = {
// 속성
color: "red",
max_diameter: 30,
min_diameter: 10,
max_radius: function() {
let max_x = this. max_diameter / 2;
return max_x;
},
min_radius : function() {
let min_x = this.min_diameter / 2;
return min_x;
}
};
// red의 색상을 blue로 바꿈
star.color = 'blue';
document.write("별의 색상 : " + star.color + "<br>");
document.write("별의 바깥 둘레 : " + star.max_diameter + "<br>");
document.write("별의 바깥 둘레 반지름 : " + star.max_radius() + "<br>");
document.write("별의 안쪽 둘레 : " + star.min_diameter + "<br>");
document.write("별의 안쪽 둘레 반지름 : " + star.min_radius() + "<br>");
</script>
</body>
</html>
new Object()
new 연산자와 함수를 이용하여 객체를 정의하기 위한 형식으로 요즘은 잘 사용되지 않는다.
let 변수명 = new Object();
객체 속성 = 속성값 ;
...
객체 메서드 = function() {함수구문};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let myCar = new Object();
myCar.type = "BMW";
myCar.color = "black";
myCar.speed = 100;
myCar.break = function() {
this.speed -= 10;
return this.speed;
};
myCar.accel = function() {
this.speed += 10;
return this.speed;
}
document.write("myCar : " + myCar.type + ", 색상 : " + myCar.color + ", 속력 : " + myCar.accel());
</script>
</body>
</html>
'웹 프로그래밍 기초 > 객체' 카테고리의 다른 글
class문법 활용한 객체 정의 (0) | 2025.04.07 |
---|---|
class문법 활용한 객체 정의 (0) | 2025.04.07 |
생성자 함수를 이용한 객체 정의 (0) | 2025.04.07 |
메서드 (0) | 2025.04.07 |
객체란 (0) | 2025.04.07 |