웹프로그래밍/HTML CSS JavaScript

[JavaScript] 리터럴 객체 / 동적함수 / 객체생성자함수

아잠만_ 2024. 5. 7. 17:34

리터럴 객체

  • const 이름 = {
    key : "value" (변수 추가)

    메서드 이름: function() { }
    메서드 이름() { }
    }

  • 메서드 속성 선언 이후 추가시
    객체이름.변수이름 = 
    객체이름.메서드 이름 = function(){ }

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	// 객체 정의 선언
	const rect = {

		width : 10,
		height : 5,
		
// 		getArea : function() {
// 			return this.width * this.height;
// 		}
	
		getArea() {
			return this.width * this.height;	// this 생략X
		}
	}
	
	// rect 객체에 getCircum()메소드를 동적으로 추가
// rect.getCircum = function() {
	
// }
	
rect.getCircum = function() {
	return (parseInt(this.width) + parseInt(this.height) )*2;
}
	
function proc1() {
	// 객체 사용
// 	let vw = rect.width;
// 	let vh = rect.height;
// 	let va = rect.getArea();
	
	// 출력
	printRect('result1');
}
console.log(rect);
function proc2() {

	rect.width = prompt("너비 입력");
	rect.height = prompt("높이 입력");

	// 객체 사용
// 	let vw = rect.width;
// 	let vh = rect.height;
// 	let va = rect.getArea();
	
	// 출력
	printRect('result2');
}

function proc3() {

	// name 속성은 rect객체에 선언 되지 않은 속성
	// 동적으로 필요 시 추가가 가능하다
	rect.name = prompt("이름 입력");	// 이름이 없어도 동적으로 추가됨
	rect.color = prompt("색 입력");

	// 객체 사용
// 	let vw = rect.width;
// 	let vh = rect.height;
// 	let va = rect.getArea();
	
	// 출력
	printRect('result3');
}
const printRect = res => {
	let disp = '';
	let rname = '';
	let rcolor = '';
    if (typeof rect.name != 'undefined') {
    	rname = rect.name;
    } 
    if (typeof rect.color != 'undefined') {
    	rcolor = rect.color;
    }
        disp += `이름 : ${rname} <br>`;
        disp += `색상 : ${rcolor} <br>`;
        disp += `너비 : ${rect.width} <br>`;
        disp += `높이 : ${rect.height} <br>`;
        disp += `넓이 : ${rect.getArea()} <br>`;
        disp += `둘레 : ${rect.getCircum()} <br>`;
document.getElementById(res).innerHTML = disp;
}
</script>
</head>
<body>

	<div class="box">
		<h3>
			리터럴 객체 생성<br> const rect = { key : "value" }
		</h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
	
	<div class="box">
		<h3>
			리터럴 객체 생성<br> const rect = { key : "value" }<br>가로세로를 입력받음
		</h3>
		<input type="button" value="확인" onclick="proc2()"> <br> <br>

		<div id="result2"></div>
	</div>
	
	<div class="box">
		<h3>
			리터럴 객체 생성<br> const rect = { key : "value" }<br>name과 color를 추가
		</h3>
		<input type="button" value="확인" onclick="proc3()"> <br> <br>

		<div id="result3"></div>
	</div>
</body>
</html>

객체 const 밖에서 속성을 선언하는 것도 가능하다

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	// 객체 정의 선언
	const rect = {

	}
	

// rect객체 밖에서 속성들을 동적으로 추가
// rect.width = 5;
// rect.height = 4;

rect.getCircum = function() {
	return (parseInt(this.width) + parseInt(this.height) )*2;
}
	
function proc1() {
	// 메서드 안에서도 속성 추가 가능
	rect.width = 5;
	rect.height = 4;
	rect.name = "네모";
	rect.getArea = function(){
		return this.width * this.height;
	}

	
	// 출력
	printRect('result1');
}
console.log(rect);

const printRect = res => {
	let disp = '';
	let rname = '';
	let rcolor = '';
    if (typeof rect.name != 'undefined') {
    	rname = rect.name;
    } 
    if (typeof rect.color != 'undefined') {
    	rcolor = rect.color;
    }
        disp += `이름 : ${rname} <br>`;
        disp += `색상 : ${rcolor} <br>`;
        disp += `너비 : ${rect.width} <br>`;
        disp += `높이 : ${rect.height} <br>`;
        disp += `넓이 : ${rect.getArea()} <br>`;
        disp += `둘레 : ${rect.getCircum()} <br>`;
document.getElementById(res).innerHTML = disp;
}
</script>
</head>
<body>

	<div class="box">
		<h3>
			리터럴 객체 생성<br> const rect = { key : "value" }
		</h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
</body>
</html>

객체생성자함수

  • function 객체이름(변수){ 
    this.변수 = 변수

    this.함수 = function(){ }
    }

  • 나중에 동적으로 속성 추가시
    객체이름.변수 = 

    객체이름.메서드 이름 = function(){ }
    객체이름.prototype.메서드이름 = function() { } // 함수로 선언했을 때만 가능

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function Rect(width, height) {
	this.width = width;
	this.height = height;
	
	this.getArea = function(){
		return this.width * this.height;
	}
// 	this.getCircum = function(){
// 		return (parseInt(this.width)+parseInt(this.height))*2;
// 	}
}

// 함수 선언 후 동적으로 추가
Rect.prototype.getCircum = function() {
	return (parseInt(this.width)+parseInt(this.height))*2;
}

const proc1 = () => {
	// 객체 생성
	const p1 = new Rect(2,3);
	
	// name 속성을 동적으로 추가 - p1객체만 사용, 다른 객체는 사용 불가
	p1.name = "네모";
	console.log(p1);
	
	//getCircum()를 동적으로 추가 - p1객체만 사용
// 	p1.getCircum = function() {
// 		return (parseInt(this.width)+parseInt(this.height))*2;
// 	}
	
	printRect('result1', p1);
}

const proc2 = () => {
	// 객체 생성
	const p2 = new Rect(5,8);
	p2.name="사각형";
	console.log(p2);
	
	printRect('result2', p2);
}

const printRect = (result, p) => {
	disp = `너비 : ${p.width} <br>
			높이 : ${p.height}<br>
			이름 : ${p.name}<br>
			면적 : ${p.getArea()} <br>
			둘레 : ${p.getCircum()}`;
	
	document.getElementById(result).innerHTML =disp;
}
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
	
	<div class="box">
		<h3></h3>
		<input type="button" value="확인" onclick="proc2()"> <br> <br>

		<div id="result2"></div>
	</div>
</body>
</html>

함수에 변수를 직접 입력하지 않고 undefined인지 확인하고 직접 대입받는 형식도 가능

예시
if(typeof width == 'undefined'){
this.width = prompt("너비 입력");
} else{
this.width = width;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function Rect(width, height) {
	
	if(typeof width == 'undefined'){
		this.width = prompt("너비 입력");
	} else{
		this.width = width;
	}
	
	if(typeof height == 'undefined'){
		this.height = prompt("높이 입력");
	}else {
		this.height = height;
	}
	
	this.getArea = function(){
		return this.width * this.height;
	}
// 	this.getCircum = function(){
// 		return (parseInt(this.width)+parseInt(this.height))*2;
// 	}
}

// 함수 선언 후 동적으로 추가
Rect.prototype.getCircum = function() {
	return (parseInt(this.width)+parseInt(this.height))*2;
}

const proc1 = () => {
	// 객체 생성
	const p1 = new Rect();
	
	// name 속성을 동적으로 추가 - p1객체만 사용, 다른 객체는 사용 불가
	p1.name = "네모";
	console.log(p1);
	
	//getCircum()를 동적으로 추가 - p1객체만 사용
// 	p1.getCircum = function() {
// 		return (parseInt(this.width)+parseInt(this.height))*2;
// 	}
	
	printRect('result1', p1);
}

const proc2 = () => {
	// 객체 생성
	const p2 = new Rect(5,8);
	p2.name="사각형";
	console.log(p2);
	
	printRect('result2', p2);
}

const printRect = (result, p) => {
	disp = `너비 : ${p.width} <br>
			높이 : ${p.height}<br>
			이름 : ${p.name}<br>
			면적 : ${p.getArea()} <br>
			둘레 : ${p.getCircum()}`;
	
	document.getElementById(result).innerHTML =disp;
}
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
	
	<div class="box">
		<h3></h3>
		<input type="button" value="확인" onclick="proc2()"> <br> <br>

		<div id="result2"></div>
	</div>
</body>
</html>