Study Web Development

12월 22일

이전으로

JavaScript

6. 함수

콜백 함수

  1. 새 HTML 파일 s16_parameter.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>함수를 매개 변수로 받는 함수</title>
<script type="text/javascript">
	// 함수를 10번 호출하는 함수
	function callFunctionTenTimes(otherFunction) {
		for(let i=0;i<10;i++) {
			otherFunction(); // 매개 변수로 전달된 함수를 실행
		}
	}
	
	// 선언적 함수
	function justFunction() {
		document.write('Happy Day!<br>');
	}

	// 함수를 호출하면서 전달되는 함수가 바로 실행되는 경우; 에러 발생
	// callFunctionTenTimes(justFunction());
	
	// 함수를 호출하면서 다른 함수를 매개 변수로 전달하는 경우
	callFunctionTenTimes(justFunction);
	
	document.write('--------<br>');
	
	// 익명 함수 전달
	callFunctionTenTimes(function() {
		document.write('Hello World!<br>');
	});
</script>
</head>
<body>

</body>
</html>

8. 객체 생성

8-4 생성자 함수를 이용한 객체 생성

  1. 새 HTML 파일 s09_constructor.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>생성자 함수 지정</title>
<script type="text/javascript">
	// 생성자 함수 지정; 일반적으로 생성자 함수의 이름은 대문자로 시작
	function Student(name, korean, math, english, science) {
		// 속성 지정
		this.이름 = name;
		this.국어 = korean;
		this.수학 = math;
		this.영어 = english;
		this.과학 = science;
		
		// 메서드 지정
		// 총점 구하기
		this.getSum = function() {
			return this.국어 + this.수학 + this.영어 + this.과학;
		};
		// 평균 구하기
		this.getAverage = function() {
			return this.getSum() / 4;
		};
		// 정보를 반환하는 메서드
		this.toString = function() {
			return this.이름 + ', ' + this.getSum() + ', ' + this.getAverage();
		};
	}
	
	// 생성자 함수를 이용한 객체 생성
	let student = new Student('너굴', 100, 99, 98, 97); // new 키워드는 빈 객체 {}를 만들어 this에 할당하고, 생성자 함수는 this에 새로운 속성을 추가하여 수정 후 this를 반환함
	document.write(student);
</script>
</head>
<body>

</body>
</html>
  1. 새 HTML 파일 s10_constructor.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>생성자 함수를 이용해서 객체를 생성하고 배열에 저장하기</title>
<script type="text/javascript">
	// 생성자 함수 지정
	function Student(name, kor, eng, math, sci) {
		// 속성 지정
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
		this.sci = sci;
		
		// 메서드 지정
		this.getSum = function() {
			return kor + eng + math + sci;
		};
		this.getAvg = function() {
			return this.getSum() / 4;
		};		
		this.toString = function() {
			return this.name + ', ' + this.getSum() + ', ' + this.getAvg();
		};
	}
	
	// 배열 생성
	let students = [];
	
	// 배열에 객체를 저장
	students.push(new Student('너굴', 99, 98, 97, 96));
	students.push(new Student('콩돌', 99, 98, 98, 99));
	students.push(new Student('밤돌', 95, 98, 97, 96));
	students.push(new Student('모카', 94, 98, 94, 93));
	students.push(new Student('프라페', 99, 96, 97, 97));

	// 출력
	document.write('이름, 총점, 평균<br>');
	document.write(students.join('<br>'));
</script>
</head>
<body>

</body>
</html>

8-5 프로토타입을 이용한 메서드 생성

  1. 새 HTML 파일 s11_prototype.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>프로토타입을 이용한 메서드 생성</title>
<script type="text/javascript">
	// 생성자 함수 정의
	function Student(name, kor, eng, math, sci) {
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
		this.sci = sci;
	}
	
	// 프로토타입은 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
	Student.prototype.getSum = function() {
		return this.kor + this.eng + this.math + this.sci;
	};
	Student.prototype.getAvg = function() {
		return this.getSum() / 4;
	};
	Student.prototype.toString = function() {
		return this.name + ', ' + this.getSum() + ', ' + this.getAvg();
	};
	
	// 배열 생성
	let students = [];
	
	// 배열에 객체를 저장
	students.push(new Student('초코', 99, 98, 97, 96));
	students.push(new Student('자바칩', 97, 98, 97, 94));
	students.push(new Student('얼그레이', 96, 93, 97, 96));
	students.push(new Student('브라운슈가', 95, 91, 93, 95));
	students.push(new Student('요거트', 94, 98, 62, 66));
	
	// 출력
	document.write('이름, 총점, 평균<br>');
	for(let value of students) { // 반복 가능한 객체 students에 대해 반복하고, 각 반복에 서로 다른 속성값을 value에 할당
		document.write(value.toString() + '<br>');
	}
</script>
</head>
<body>

</body>
</html>
  1. 새 HTML 파일 s12_practice.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습</title>
<script type="text/javascript">
/* 
[실습 문제]
이름		수입		지출		잔액(getBalance, 세금 공제)		세금(getTax, 5%)
홍길동	3000	2500
박문수	5000	1100
이순신	4000	3600
김유신	7000	4200
*/
	// 배열 생성
	var member = [];
	
	// 배열에 객체를 저장
	member.push({name:'바닐라', income:3000, spending:2500});
	member.push({name:'모카', income:5000, spending:1100});
	member.push({name:'초코', income:4000, spending:3600});
	member.push({name:'헤이즐넛', income:7000, spending:4200});
	
	// 객체에 메서드 추가
	for(let me of member) {
		// 잔액(세금 공제) 구하기
		me.getBalance = function() {
			return this.income - this.getTax() - this.spending;
		};	
		// 세금 구하기
		me.getTax = function() {
			return this.income * 0.05;
		};
		// 정보 반환하기
		me.toString = function() {
			let out = '';
			for(let key in this) {
				if(key.startsWith('get')) {
					out += '<td>' + this[key]() + '</td>';
				}
				else if(key !== 'toString') {
					out += '<td>' + this[key] + '</td>';
				}	
			}
			return out;
		};
	}

	// 출력
	document.write('<table>');
	document.write('<tr>');
	document.write('<th>이름</th><th>수입</th><th>지출</th><th>잔액</th><th>세금</th>');
	document.write('</tr>');
	for(let me of member) {
		document.write('<tr>');
		document.write(me);
		document.write('</tr>');
	}
	document.write('</table>');
</script>
<style type="text/css">
	table {
		border-collapse: collapse;
		margin:0;
		padding:0;
	}
	th {
		border-bottom: solid 1px black;	
		background: lightgray;
	}
	tr :first-child {
		border-right: solid 1px black;
	}
	tr td:first-child {
		text-align: center;
	}
	tr td:not(:first-child) {
		text-align: right;
	}
	th, td {
		padding: 0 2rem;
	}
</style>
</head>
<body>

</body>
</html>

9. 클라이언트 객체

9-1 클라이언트 객체의 종류

9-2 window의 속성과 메서드

  1. 새 폴더 ch09-clientObject를 생성하고 새 HTML 파일 s01_window.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window</title>
<script type="text/javascript">
/* 
브라우저 관련 객체
window
	|
	location history frame document screen navigator
							|
		anchor applet area form image layer link plugin title
							|
			button checkbox fileupload hidden password radio reset select submit text textarea

window의 메서드
alert() : 경고창
prompt() : 입력창
confirm() : 선택창
*/
	window.alert('경고창');

	var season = window.prompt('좋아하는 계절은?', '');
	document.write('좋아하는 계절은 ' + season + '이다<br>');
	
	var choice = window.confirm('홀리데이 특별 패키지를 구매합니다. 결제 금액: 33,000원'); // 확인을 클릭하면 true 반환, 취소를 클릭하면 false 반환
	if(choice) {
		document.write('결제에 성공했습니다.');
	}
	else {
		document.write('결제에 실패했습니다!')
	}
</script>
</head>
<body>

</body>
</html>
  1. 새 HTML 파일 s02_window.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window</title>
<script type="text/javascript">
/* 
window의 메서드

open(URL, 새 창 이름, 옵션) : 새 창 열기
옵션
width : 새 창의 너비
height : 새 창의 높이
location : 주소 입력창 유무
menubar : 메뉴 유무
resizable : 화면 크기 조절 가능 여부
status : 상태 표시줄 유무
toolbar : 툴바 유무
scrollbars : 스크롤바 유무

close() : 창 닫기
*/
	var win;
	
	// 새 창 열기
	function winOpen() {
		win = window.open('https://www.naver.com', 'child', 'width=400,height=300,location=no,menubar=no,resizable=no,status=no,toolbar=no,scrollbars=no'); // location, resizable, scrollbars 등 일부 옵션의 경우 브라우저가 정책적으로 무시
	}
	
	// 창 닫기
	function winClose() {
		win.close(); // 기존에 열려 있던 창 닫기
	}	
</script>
</head>
<body>
	<input type="button" value="창 열기" onclick="winOpen();"><br>
	<input type="button" value="창 닫기" onclick="winClose();">
</body>
</html>
  1. 새 HTML 파일 s03_window.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window</title>
<script type="text/javascript">
/* 
window의 메서드
setTimeout(function, millisecond) : 지정한 시간(밀리초 단위) 후에 함수를 한 번 실행
setInterval(function, millisecond) : 지정한 시간(밀리초 단위)마다 함수를 반복해서 실행
*/
	// window가 로드될 때 함수를 실행
	window.onload = function() { // 스크립트의 실행 속도를 의도적으로 지연시키기 위해 window가 모두 로드되면 호출되는 이벤트 속성 onload에 함수를 연결; <body>까지 모두 인식하고 창이 열린 다음에 창을 닫아야 하기 때문
		alert('경고창을 닫고 3초 후 이 페이지는 종료됩니다.');
		// 3초 후에 함수를 실행
		window.setTimeout(function() {
			// 현재 창 닫기
			window.close();
		}, 3000);
	};
</script>
</head>
<body>

</body>
</html>

9-6 location 객체의 속성과 메서드

  1. 새 HTML 파일 s04_location.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>location</title>
<script type="text/javascript">
	document.write('location.href : ' + location.href + '<br>'); // 전체 주소
	document.write('location.host : ' + location.host + '<br>'); // 호스트명과 포트 번호
	document.write('location.hostname : ' + location.hostname + '<br>'); // 호스트명; 도메인이 없지만 서버(=톰캣)와 클라이언트(=브라우저)가 같은 PC에 있으므로 IP 주소 대신 localhost를 반환
	document.write('location.pathname : ' + location.pathname + '<br>'); // 하위 경로; 프로젝트명 javaScript는 contextPath에 해당
	document.write('location.protocol : ' + location.protocol + '<br>');
	document.write('location.port : ' + location.port + '<br>'); // 포트 번호; 톰캣의 기본 포트는 8080번이며, 상용 서비스의 경우 80번을 사용
</script>
</head>
<body>

</body>
</html>
  1. 새 HTML 파일 s05_location.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>location</title>
</head>
<body>
	<!-- 페이지 이동 -->
	<input type="button" value="이동(href)" onclick="location.href = 's01_window.html';"> <!-- location의 href 속성에 직접 주소를 대입하면 해당 주소로 이동 -->
	<input type="button" value="이동(assign)" onclick="location.assign('s02_window.html');"> <!-- location의 assign() 메서드에 주소를 인자로 전달하면 해당 주소로 이동 -->
	<input type="button" value="이동(replace)" onclick="location.replace('s02_window.html');"> <!-- location의 replace() 메서드에 주소를 인자로 전달하면 해당 주소로 이동; 히스토리를 기록하지 않아 뒤로가기 불가 -->
	<!-- 새로고침 -->
	<input type="button" value="새로고침" onclick="location.reload();">
</body>
</html>

9-4 history 객체의 속성과 메서드

  1. 새 HTML 파일 s06_history.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>history</title>
</head>
<body>
	<!-- history의 back(), go(), forward() 메서드는 히스토리가 없는 경우 동작하지 않음 -->
	<input type="button" value="뒤로 한 페이지 이동(back)" onclick="history.back();"><br>
	<input type="button" value="뒤로 한 페이지 이동(go)" onclick="history.go(-1);"><br>
	<input type="button" value="앞으로 한 페이지 이동(forward)" onclick="history.forward();"><br>
	<input type="button" value="앞으로 한 페이지 이동(go)" onclick="history.go(1);"><br>
</body>
</html>

10. 내장 객체

10-4 Date 객체의 메서드

  1. 새 폴더 ch10-nestedObject 생성하고 새 HTML 파일 s01_Date.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Date</title>
<script type="text/javascript">
	var now = new Date(); // 생성자 함수를 이용하여 Date 객체 생성
	
	document.write('now의 값 : ' + now + '<br>');

	document.write('오늘 : ' + now.toLocaleString() + '<br>');
	document.write('오늘의 날짜 : ' + now.toLocaleDateString() + '<br>');
	document.write('오늘의 시간 : ' + now.toLocaleTimeString() + '<br>');
	
	document.write('연도 : ' + now.getFullYear() + '<br>');
	document.write('월 : ' + (now.getMonth() + 1) + '<br>'); // 0~11로 반환
	document.write('일 : ' + now.getDate() + '<br>');
	document.write('요일 : ' + now.getDay() + '<br>'); // 요일을 숫자로 반환; 0=일요일, 6=토요일
	document.write('시 : ' + now.getHours() + '<br>'); // 0~23으로 반환; 12시 표기법은 별도의 연산 필요
	document.write('분 : ' + now.getMinutes() + '<br>');
	document.write('초 : ' + now.getSeconds() + '<br>');
	document.write('밀리초 : ' + now.getMilliseconds() + '<br>');
</script>
</head>
<body>

</body>
</html>
  1. 새 HTML 파일 s02_Date.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Date</title>
<script type="text/javascript">
	// <body> <span> 태그를 인식할  있게 하기 위해 스크립트 실행을 지연시킴
	window.onload = function() {
		// 지정한 시간마다 매개 변수로 전달된 함수를 반복해서 실행
		window.setInterval(function() {
			var time = new Date();
			var hours = time.getHours();
			var minutes = time.getMinutes();
			var seconds = time.getSeconds();
			
			var clock = '';
			clock += ((hours < 10) ? '0' : '') + hours;
			clock += ((minutes < 10) ? ':0' : ':') + minutes;
			clock += ((seconds < 10) ? ':0' : ':') + seconds;
			
			
			// ID를 통해 태그를 검색하고, innerHTML 속성을 통해 태그의 내용을 제어
			document.getElementById('display').innerHTML = clock; 
		}, 1000);
	};
</script>
</head>
<body>
	<span id="display"></span>
</body>
</html>

10-5 Math 객체의 속성과 메서드

  1. 새 HTML 파일 s03_Math.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Math</title>
<script type="text/javascript">
	document.write('Math.ceil(5.3) : ' + Math.ceil(5.3) + '<br>'); // 올림
	document.write('Math.floor(5.9) : ' + Math.floor(5.9) + '<br>'); // 버림
	document.write('Math.round(5.6) : ' + Math.round(5.6) + '<br>'); // 반올림
	
	document.write('Math.max(15, 30) : ' + Math.max(15, 30) + '<br>'); // 최댓값
	document.write('Math.max(15, 32, 103, 57, 273) : ' + Math.max(15, 32, 103, 57, 273) + '<br>'); // 최댓값; 인자 수 제약 없음
	
	document.write('Math.min(15, 30) : ' + Math.min(15, 30) + '<br>'); // 최솟값
	document.write('Math.min(15, 32, 103, 57, 273, 0) : ' + Math.min(15, 32, 103, 57, 273, 0) + '<br>'); // 최솟값; 인자 수 제약 없음
	
	document.write('Math.abs(-5) : ' + Math.abs(-5) + '<br>'); // 절대값
	document.write('Math.random() : ' + Math.random() + '<br>'); // 0부터 1 사이의 난수
	
	document.write('--------<br>');
	
	var newNum = 254.437;
	document.write('소수점 이하 셋째 자리에서 반올림 : ' + newNum.toFixed(2)); // Number 객체의 toFixed() 메서드는 숫자를 고정 소수점 표기법으로 나타낸 문자열로 반환함
</script>
</head>
<body>

</body>
</html>

다음으로