<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
* {
	margin: 0; padding: 0;
    box-sizing: border-box;
}

body {
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
}

a {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
a:active, a:hover {
	text-decoration: underline;
	color: #F28011;
}

.btn {
	color: #333;
	border: 1px solid #333;
	background-color: #fff;
	padding: 4px 10px;
	border-radius: 4px;
	font-weight: 500;
	cursor:pointer;
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.btn:hover, .btn:active, .btn:focus {
	background-color: #e6e6e6;
	border-color: #adadad;
	color:#333;
}
.boxTF {
	border: 1px solid #999;
	padding: 5px 5px;
	background-color: #fff;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.selectField {
	border: 1px solid #999;
	padding: 4px 5px;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}

.boxTA {
    border:1px solid #999;
    height:150px;
    padding:3px 5px;
    border-radius:4px;
    background-color:#fff;
	resize : none;
	vertical-align: baseline;
}

textarea:focus, input:focus {
	outline: none;
}

.title {
	width:100%;
	font-size: 16px;
	font-weight: bold;
	padding: 13px 0;
}

.container {
    width: 400px;
    margin: 30px auto;
}

.table {
	width: 100%;
	border-spacing: 0;
	border-collapse: collapse;
}

.table th, .table td {
	padding: 7px 0;
}

.table-border tr {
	border-bottom: 1px solid #ccc; 
}
.table-border tr:first-child {
	border-top: 2px solid #ccc;
}

</style>
<script type="text/javascript">

</script>
<script type="text/javascript">
function itemAdd() {
	var f = document.noteForm;
	var item = f.itemLeft;
	
	// select 요소에 option 요소 추가
	item[item.length] = new Option("김자바", "kim"); // text, value
	item[item.length] = new Option("스프링", "spring");
	item[item.length] = new Option("서블릿", "servlet");
	item[item.length] = new Option("오라클", "oracle");
	item[item.length] = new Option("이자바", "lee");
	item[item.length] = new Option("홍자바", "hong");
	item[item.length] = new Option("나대한", "na");
}

window.onload = () => itemAdd();

// 선택된 option을 좌 또는 우로 이동 
function itemMove(pos) {
	var f = document.noteForm;
	var source, target;
	
	if( pos==="left" ) { // right -> left
		source = f.itemRight;
		target = f.itemLeft;
	} else { // left -> right
		source = f.itemLeft;
		target = f.itemRight;
	}
	
	var len = source.length;
	for(var i =0; i<len; i++) {
		if(source.options[i].selected) { // 선택된 항목만
			target[target.length] = 
				new Option(source.options[i].text, source.options[i].value);
			source[i] = null; // 삭제
			i--;
			len--;
		}
	}
	
}

// 모든 option을 좌 또는 우로 이동
function itemAllMove(pos) {
	var f = document.noteForm;
	var source, target;
	
	if( pos==="left" ) { // right -> left
		source = f.itemRight;
		target = f.itemLeft;
	} else { // left -> right
		source = f.itemLeft;
		target = f.itemRight;
	}
	
	var len = source.length;
	for(var i =0; i<len; i++) {
		target[target.length] = new Option(source.options[0].text, source.options[0].value);
		source[0] = null; // 삭제
	}
	
}

function sendOk() {
	var f = document.noteForm;
	
	if( f.itemRight.length === 0 ) {
		alert("받는 사람을 먼저 추가 하세요...");
		f.itemRight.focus();
		return;
	}
	
	if(! f.msg.value.trim() ) {
		alert("메시지를 입력하세요...");
		f.msg.focus();
		return;
	}
	
	// select 요소는 서버로 전송하기 위해서 반드시 항목들이 선택되어 있어야 한다.
	for(var i=0; i < f.itemRight.length; i++) {
		f.itemRight[i].selected = true; // select 항목 선택
	}	
	
	alert("메시지 전송...");
	
}

</script>


</head>
<body>

<div class="container">

	<div class="title">
	   <h3><span>|</span> 쪽지 보내기</h3>
	</div>

	<form name="noteForm" method="post">
	<table class="table">
	<tr>
	    <td width="150"><span>친구목록</span></td>
	    <td width="100">&nbsp;</td>
	    <td width="150"><span>받는사람</span></td>
	</tr>
	
	<tr>
	    <td style="padding-left: 10px;">
	        <select name="itemLeft" multiple="multiple" class="selectField" style="width:130px; height:120px;"></select>
	    </td>
	    <td align="center">
		    <button type="button" class="btn" onclick="itemMove('right');" style="display:block; width:80px;"> &gt; </button>
		    <button type="button" class="btn" onclick="itemAllMove('right');" style="display:block;width:80px;"> &gt;&gt; </button>
		    <button type="button" class="btn" onclick="itemMove('left');" style="display:block;width:80px;"> &lt; </button>
		    <button type="button" class="btn" onclick="itemAllMove('left');" style="display:block;width:80px;"> &lt;&lt; </button>
	    </td>
	    <td style="padding-left: 10px;">
	        <select name="itemRight" multiple="multiple" class="selectField" style="width:130px; height:120px;">
	        </select>
	    </td>
	</tr>
	<tr>
	    <td colspan="3">
	       <span>메시지</span>
	    </td>
	</tr>
	<tr>
	    <td colspan="3" style="padding-left: 10px;">
	        <textarea name="msg" class="boxTA" style="height:60px; width: 98%;"></textarea>
	    </td>
	</tr>
	</table>
	
	<table class="table">
	<tr>
	    <td align="right" style="padding-right: 10px;">
	        <button type="button" class="btn" onclick="sendOk();"> 쪽지보내기 </button>
	    </td>
	</tr>
	</table>
	</form> 

</div>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
*{
	margin: 0; padding: 0;
    box-sizing: border-box;
}

body {
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
}

a {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
a:active, a:hover {
	text-decoration: underline;
	color: #F28011;
}

.btn {
	color: #333;
	border: 1px solid #333;
	background-color: #fff;
	padding: 4px 10px;
	border-radius: 4px;
	font-weight: 500;
	cursor:pointer;
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline; /* 부모 요소의 기준선에 맞춤 */
}
.btn:hover, .btn:active, .btn:focus {
	background-color: #e6e6e6;
	border-color: #adadad;
	color:#333;
}
.boxTF {
	border: 1px solid #999;
	padding: 5px 5px;
	background-color: #fff;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.selectField {
	border: 1px solid #999;
	padding: 4px 5px;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}

textarea:focus, input:focus {
	outline: none;
}

.member {
	width: 600px; margin: 30px auto 25px;
}

.title {
	width:100%;
	font-size: 16px;
	font-weight: bold;
	padding: 13px 0;
}

.table {
	width: 100%;
	border-spacing: 0;
	border-collapse: collapse;
}

.table th, .table td {
	padding: 7px 0;
}

.table-border tr {
	border-bottom: 1px solid #ccc; 
}
.table-border tr:first-child {
	border-top: 2px solid #ccc;
}

.table-form tr td:first-child{
	background: #e6e6e6;
	text-align: center;
	width: 120px;
}

.table-form tr td:nth-child(2) {
	text-align: left;
	padding-left: 10px; 
}

.table-form input[type=text]:focus, .table-form input[type=password]:focus {
	border: 1px solid tomato;
}
</style>

<script type="text/javascript">
function isValidDateFormat(date) {
	if(date.length !=8 && date.length != 10) return false;
	
	var p = /(\.)|(\-)|(\/)/g;
	date = date.replace(p, "");
	
	var format = /^[12][0-9]{7}$/;
	if(! format.test(date) ) return false;
	
	var y = parseInt( date.substr(0,4) );
	var m = parseInt( date.substr(4,2) );
	var d = parseInt( date.substr(6) );
	
	if(m<1 || m>12) return false;
	
	var lastDay = (new Date(y,m,0)).getDate();
	if(d<1 || d>lastDay) return false;
	
	return true;
}


function memberOk() {
	var f = document.memberForm;
	var s;
	
	// 아이디는 5~10자 이며 영문자로 시작하고 영숫자와_로 구성
	// i 대소문자를 구분하지 않음 [a-zA-Z] 와 같은 의미
	// \w 영어, 숫자, _ 까지 가능
	if(! /^[a-z]\w{4,9}$/i.test(f.userId.value)) {
		alert("아이디는 영문자로 시작하며, 5~10자이내의 영숫자로 구성합니다.")
		f.userId.focus();
		return;
	}
	
	// 패스워드는 5~10자이며 영문자와 하나이상의 숫자 또는 특수문자를 포함해야함
	s = f.userPwd.value;
	if( ! /^(?=.*[a-z])(?=.[!@#$%^&*-=+]|.*[0-9]).{5,10}$/i.test(s)) {
		alert("패스워드는 5~10자 이내로 영문자와 숫자 또는 특수문자로 구성합니다.");
		f.userPwd.focus();
		return;
	}
	
	
	if( s != f.userPwd1.value ) {
		alert("패스워드가 일치하지 않습니다.");
		f.userPwd.focus();
		return;
	}
	
	// 이름은 한글 2~5자 이내이거나 영어 이름 : 이름(2~20) 성(2~20)
	
	// 이름은 한글 2~5자 이내
	s = f.userName.value;
	if(! /^[가-힣]{2,5}$/.test(s) ) {
		alert("이름을 입력하세요");
		f.userName.focus();
		return;
	}
	
	// 생년월일
	if(! isValidDateFormat(f.birth.value) ) {
		alert("생년월일 입력하세요");
		f.birth.focus();
		return;
	}
	
	if(! f.email1.value.trim() ) {
		alert("이메일을 입력하세요");
		f.email1.focus();
		return;
	}
	
	if(! f.email2.value.trim() ) {
		alert("이메일을 입력하세요");
		f.email2.focus();
		return;
	}
	
	if(! f.tel1.value ) {
		alert("전화번호를 입력하세요");
		f.tel1.focus();
		return;
	}
	
	if(! /^\d{3,4}$/.test(f.tel2.value) ) {
		alert("전화번호를 입력하세요");
		f.tel2.focus();
		return;
	}
	
	if(! /^\d{4}$/.test(f.tel3.value) ) {
		alert("전화번호를 입력하세요");
		f.tel3.focus();
		return;
	}
	
	alert("회원 가입 성공 ^^");
}

function changeEmail() {
	var f = document.memberForm;
	var s = f.selectEmail.value;
	
	if(s === "direct") {
		f.email2.value = "";
		f.email2.readOnly = false;
		f.email1.focus();		
	} else {
		f.email2.value = s;
		f.email2.readOnly = true;
		f.email1.focus();
	}
	
}

</script>

</head>
<body>

<div class="member">
	<div class="title">
		<h3><span>|</span> 회원 가입</h3>
	</div>
	
	<form name="memberForm" method="post">
	<table class="table table-border table-form">
		<tr>
			<td>아&nbsp;이&nbsp;디</td>
			<td>
				<input type="text" name="userId" id="userId" maxlength="10" class="boxTF" style="width: 50%;">
			</td>
		</tr>
	
		<tr>
			<td>패스워드</td>
			<td>
				<input type="password" name="userPwd" class="boxTF" maxlength="10" style="width: 50%;">
			</td>
		</tr>
	
		<tr>
			<td>패스워드 확인</td>
			<td >
				<input type="password" name="userPwd1" class="boxTF" maxlength="10" style="width: 50%;">
			</td>
		</tr>
	
		<tr>
			<td>이&nbsp;&nbsp;&nbsp;&nbsp;름</td>
			<td>
				<input type="text" name="userName" maxlength="10" class="boxTF" style="width: 50%;">
			</td>
		</tr>
	
		<tr>
			<td>생년월일</td>
			<td>
				<input type="date" name="birth" class="boxTF" style="width: 50%;">
			</td>
		</tr>
	
		<tr>
			<td>이 메 일</td>
			<td>
				  <select name="selectEmail" class="selectField" onchange="changeEmail();">
						<option value="">선 택</option>
						<option value="naver.com">네이버 메일</option>
						<option value="hanmail.net">한 메일</option>
						<option value="hotmail.com">핫 메일</option>
						<option value="gmail.com">지 메일</option>
						<option value="direct">직접입력</option>
				  </select>
				  <input type="text" name="email1" maxlength="30" class="boxTF" style="width: 33%;"> @ 
				  <input type="text" name="email2" maxlength="30" class="boxTF" style="width: 33%;" readonly="readonly">
			</td>
		</tr>
		
		<tr>
			<td>전화번호</td>
			<td>
				  <select name="tel1" class="selectField">
						<option value="">선 택</option>
						<option value="010">010</option>
						<option value="02">02</option>
						<option value="031">031</option>
						<option value="032">032</option>
						<option value="033">033</option>
						<option value="041">041</option>
						<option value="042">042</option>
						<option value="043">043</option>
						<option value="044">044</option>
						<option value="051">051</option>
						<option value="052">052</option>
						<option value="053">053</option>
						<option value="054">054</option>
						<option value="055">055</option>
						<option value="061">061</option>
						<option value="062">062</option>
						<option value="063">063</option>
						<option value="064">064</option>
						<option value="070">070</option>
				  </select>
				  <input type="text" name="tel2" maxlength="4" class="boxTF" style="width: 33%;"> -
				  <input type="text" name="tel3" maxlength="4" class="boxTF" style="width: 33%;">
			</td>
		</tr>
	
		<tr>
			<td>우편번호</td>
			<td>
				<input type="text" name="zip" maxlength="7" class="boxTF" readonly="readonly" style="width: 50%;">
				<button type="button" class="btn">우편번호검색</button>
			</td>
		</tr>
		
		<tr>
			<td valign="top">주&nbsp;&nbsp;&nbsp;&nbsp;소</td>
			<td>
				<label style="display: block;">
					<input type="text" name="addr1" maxlength="50" class="boxTF" readonly="readonly" style="width: 96%;">
				</label>
				<label style="display: block; margin-top: 2px;">
					<input type="text" name="addr2" maxlength="50"  class="boxTF" style="width: 96%;">
				</label>
			</td>
		</tr>
		
		<tr>
			<td>직&nbsp;&nbsp;&nbsp;&nbsp;업</td>
			<td>
				<input type="text" name="job" maxlength="10" class="boxTF" style="width: 50%;">
			</td>
		</tr>
	</table>
	
	<table class="table">
		<tr>
			<td align="center">
			    <button type="button" class="btn" onclick="memberOk();"> 회원가입 </button>
			    <button type="reset" class="btn"> 다시입력 </button>
			    <button type="button" class="btn"> 가입취소 </button>
			</td>
		</tr>
		
		<tr height="40">
			<td align="center">
				<span style="color: blue;"></span>
			</td>
		</tr>
	</table>
	</form>
	
</div>	

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
* {
	margin: 0; padding: 0;
    box-sizing: border-box;
}

body {
	font-size: 14px;
	font-family: "Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif;
}

a {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
a:active, a:hover {
	text-decoration: underline;
	color: #F28011;
}

.btn {
	color: #333;
	border: 1px solid #333;
	background-color: #fff;
	padding: 4px 10px;
	border-radius: 4px;
	font-weight: 500;
	cursor:pointer;
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.btn:hover, .btn:active, .btn:focus {
	background-color: #e6e6e6;
	border-color: #adadad;
	color:#333;
}
.boxTF {
	border: 1px solid #999;
	padding: 5px 5px;
	background-color: #fff;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.selectField {
	border: 1px solid #999;
	padding: 4px 5px;
	border-radius: 4px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}

.board {
	margin: 30px auto;
	width: 700px;
}

.title {
	width:100%;
	font-size: 16px;
	font-weight: bold;
	padding: 13px 0;
}

.table {
	width: 100%;
	border-spacing: 0;
	border-collapse: collapse;
}

.table th, .table td {
	padding: 10px 0;
}

.table-border tr {
	border-bottom: 1px solid #ccc; 
}
.table-border thead tr:first-child {
	border-top: 2px solid #ccc;
}

.table-list thead tr:first-child{
	background: #eee;
}
.table-list td {
	text-align: center;
}

.table-list td:nth-child(6n+3) {
	text-align: left;
	padding-left: 5px; 
}

.table-list tbody tr:hover {
	background: #efffef;
}

.table-list .chk {
	width: 40px;
	color: #787878;
}
.table-list .num {
	width: 60px;
	color: #787878;
}
.table-list .subject {
	color: #787878;
}

.table-list .name {
	width: 100px;
	color: #787878;
}
.table-list .date {
	width: 100px;
	color: #787878;
}
.table-list .hit {
	width: 70px;
	color: #787878;
}

.paginate {
	clear: both;
	text-align: center;
	white-space: nowrap;
	font-size: 14px;	
}
.paginate a {
	border: 1px solid #ccc;
	color: #000;
	font-weight: 600;
	text-decoration: none;
	padding: 3px 7px;
	margin-left: 3px;
	vertical-align: middle;
}
.paginate a:hover, .paginate a:active {
	color: #6771ff;
}
.paginate span {
	border: 1px solid #e28d8d;
	color: #000;
	font-weight: 600;
	padding: 3px 7px;
	margin-left: 3px;
	vertical-align: middle;
}
.paginate :first-child {
	margin-left: 0;
}
</style>

<script type="text/javascript">
function check() {
	var f = document.listForm;
	
	// checkbox 이름이 nums 인 요소가 한 개도 없는 경우
	if( f.nums === undefined ) { // if(! f.nums ) {
		return;
	}
	
	// checkbox 이름이 nums 인 요소가 한 개인 경우
	if( f.nums.length === undefined ) {
		f.nums.checked = f.chkAll.checked;
	}
	
	// checkbox 이름이 nums 인 요소가 두 개 이상인 경우
	// 동일한 이름은 객체가 두 개 이상인 경우에만 length속성이 존재한다.
	// checked 속성 : checkbox, radio 버튼을 선택/해제하거나 선택 유무를 true/false로 반환
	for(var i=0; i < f.nums.length; i++){
		f.nums[i].checked = f.chkAll.checked;
	}
}

function deleteList() {
	var f = document.listForm;
	var cnt = 0;
	
	if( ! f.nums ){
		return;
	}
	
	if( f.nums.length ) {
		// nums가 여러 개인 경우
		for(var i=0; i<f.nums.length; i++){
			if(f.nums[i].checked) {
				cnt++;
			}
		}
	} else {
		// nums가 하나인 경우
		if(f.nums.checked) {
			cnt++;
		}
	}
	
	if( cnt === 0 ){
		alert("삭제할 게시물을 먼저 선택하세요");
		return;
	}
	
	if( confirm("선택한 게시글을 삭제하시겠습니까 ? ")) {
		alert("삭제 Ok...");
		
	}
}
	
</script>

</head>
<body>

<div class="board">

	<div class="title">
	    <h3><span>|</span> 게시판</h3>
	</div>

	<table class="table">
	   <tr>
		  <td align="left" width="50%">
		  	<button type="button" class="btn" onclick="deleteList();">삭제</button>
		  </td>
		  <td align="right">
			 <select name="rows" id="rows" class="selectField">
				   <option value="5">5개씩 출력</option>
				   <option value="10" selected="selected">10개씩 출력</option>
				   <option value="20">20개씩 출력</option>
				   <option value="30">30개씩 출력</option>
				   <option value="50">50개씩 출력</option>
			 </select>
		  </td>
	   </tr>
	</table>

	<form name="listForm" method="post">
	<table class="table table-border table-list">
	<thead>
		<tr> 
			<th class="chk">
				<input type="checkbox" name="chkAll" id="chkAll" onclick="check();" style="margin-top: 3px;">        
			</th>
			<th class="num">번호</th>
			<th class="subject">제목</th>
			<th class="name">작성자</th>
			<th class="date">작성일</th>
			<th class="hit">조회수</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td><input type="checkbox" name="nums" value="2" style="margin-top: 3px;"></td> 
			<td>2</td>
			<td>
				<a href="">HTML 강좌...</a>
			</td>
			<td>홍길동</td>
			<td>2017-03-03</td>
			<td>1</td>
		</tr>

		<tr> 
			<td><input type="checkbox" name="nums" value="1" style="margin-top: 3px;"></td> 
			<td>1</td>
			<td>
				<a href="">자바 강좌...</a>
			</td>
			<td>김자바</td>
			<td>2017-01-10</td>
			<td>1</td>
		</tr>
	</tbody>
	</table>
	</form>
	
	<table class="table">
		<tr height="50">
			<td align="center">
				<div class="paginate">
					<span>1</span>
					<a href="#">2</a>
					<a href="#">3</a>
				</div>
			</td>
	   </tr>
	</table>

	<table class="table">
		<tr height="45">
			<td width="100">
				<button type="button" class="btn">새로고침</button>
			</td>
			<td align="center">
				<form name="searchForm" action="" method="post">
					<select name="condition" class="selectField">
						<option value="all">제목+내용</option>
						<option value="name">작성자</option>
						<option value="regDate">등록일</option>
						<option value="subject">제목</option>
						<option value="content">내용</option>
					</select>
					<input type="text" name="keyword" value="" class="boxTF">
					<button type="button" class="btn">검색</button>
				</form>
			</td>
			<td align="right" width="100">
				<button type="button" class="btn">글올리기</button>
			</td>
		</tr>
	</table>

</div>

</body>
</html>

 

document.forms 객체

- document.forms 속성은 현재 문서의 <form>요소 목록(HTMLCollection)을 반환한다.

- forms 객체는 html 문서의<form> 태그를 자바스크립트로 접근하기 위한 것으로 내장객체 계층 구조에서 document의 하위에 있다.

 

document.forms 객체를 이용한<form>요소 접근

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
function send() {
	var f = document.forms[0];
	
	// elements : FORM 요소에 담긴 form 컨트롤 배열 반환
	// form controll : input, button, select, textarea ...
	for(var i=0; i<f.elements.length-1; i++){
		if(! f.elements[i].value){
			alert("필수 입력 사항 입니다.");
			f.elements[i].focus();
			return;
		}
	} 
	
	var s = f.elements[0].value + ", " + f.elements[1].value;
	alert(s);
	
}

</script>

</head>
<body>

<h3>form 접근 : document.forms로 접근</h3>

<form>
	<p> 이름 : <input type="text"></p>
	<p> 과목 : <input type="text"></p>
	<p>
		<button type="button" onclick="send()">등록하기 </button>
	</p>
</form>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function send() {
	var f = document.myForm;
	
	if(! f.name.value) {
		f.name.focus();
		return;
	}
	
	if(! f.subject.value) {
		f.subject.focus();
		return;
	}
	
	var s = f.name.value + ", " + f.subject.value;
	alert(s);
	
}

</script>

</head>
<body>

<h3>form 접근 : 'document.폼이름' 으로 접근</h3>

<form name="myForm">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 과목 : <input type="text" name="subject"></p>
	<p>
		<button type="button" onclick="send()">등록하기 </button>
	</p>
</form>

</body>
</html>

 

이벤트(events)

- form에서 발생하는 이벤트를 처리하기 위해서는 addEventListener()메소드를 이용하거나 form 태그의 oneventname속성에 이벤트 리스너를 등록하여 처리한다.

- form에서 발생하는 이벤트

1. reset 이벤트

- form 내용을 reset할 때 발생하는 이벤트로, 입력 양식이 초기화 되기 전에 실행할 내용을 처리한다.

- form 태그의 onreset 속성에 이벤트 리스너를 등록하여 처리할 수 있다.

2. submit 이벤트

- form의 내용을 submit할 때 form 요소 자체에서 발생하는 이벤트로, form의 내용이 서버로 전송되기 전에 유효성 검사 등을 처리한다.

- submit버튼을 클릭할 때 발생하며, form.submit() 메소드를 직접 호출할 때는 발생하지 않는다.

submit 버튼 : <button>, <input type="submit">, <input type="image"> 등

- form 태그의 onsubmit 속성에 이벤트 리스너를 등록하여 처리할 수 있으며, onsubmit 속성에서 false를 반환하면 이벤트가 취소된다.

- 이벤트 핸들러에서 event.preventDefault() 메소드를 호출하면 submit 이벤트는 취소된다.

 

 

submit 

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>

<h3>submit 버튼 - 유효성 검사를 하지 않는 경우</h3>
<form action="request.jsp" name="myForm" method="post">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 나이 : <input type="text" name="age"></p>
	<p>
		<button type="submit">전송하기</button>
		<!-- 서버로 전송할 수 있는 기능을 가지고 있는 버튼 : submit 버튼, image 버튼 -->
		<!-- <button>에서 type="submit"을 생략하면 submit 버튼 -->
		<!-- submit 버튼, image 버튼 등은 form 태그 안에 있어야 한다. -->
	</p>
</form>


</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function check() {
	var f = document.myForm;
	
	if(! f.name.value){
		alert("이름을 입력하세요.");
		f.name.focus();
		return false; // 이벤트 취소
	}
	
	if(! /^(\d)+$/.test(f.age.value)) {
		alert("나이는 숫자만 가능합니다.");
		f.age.focus();
		event.preventDefault(); // 이벤트 취소
		return;
	}
	
	return true; // 서버로 전송
	// submit 버튼에서는 submit() 메소드를 호출하면 서버로 두 번 전송되므로 절대로 호출해서는 안된다.
	// submit 버튼은 자바스크립트에 오류가 있는 경우 스크립트를 실행하지 않고 바로 서버로 전송하므로 주의해야 한다.	
}
</script>

</head>
<body>

<h3>submit 버튼 - 유효성 검사</h3>
<form action="request.jsp" name="myForm" method="post" onsubmit="return check();">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 나이 : <input type="text" name="age"></p>
	<p>
		<button type="submit">전송하기</button>
		<!-- submit 버튼을 클릭하면 submit 이벤트가 발생한다. -->
		<!-- submit 이벤트는 false를 반환하거나 event.preventDefault()를 호출하면 이벤트가 취소 된다. -->
	</p>
</form>


</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function check() {
	var f = document.myForm;
	
	if(! f.name.value){
		alert("이름을 입력하세요.");
		f.name.focus();
		event.preventDefault(); // 이벤트 취소
		// 이 예제는 return false; 로는 이벤트 취소 발생되지 않음.
		return; 
	}
	
	if(! /^(\d)+$/.test(f.age.value)) {
		alert("나이는 숫자만 가능합니다.");
		f.age.focus();
		event.preventDefault();
		return;
	}
	
	return true; // 서버로 전송
}

// form에 submit 이벤트 등록 
/*
window.onload = function() {
	document.myForm.addEventListener("submit", check);
};
*/
window.onload = () => document.myForm.addEventListener("submit", check);

</script>

</head>
<body>

<h3>submit 버튼 - 유효성 검사</h3>
<form action="request.jsp" name="myForm" method="post">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 나이 : <input type="text" name="age"></p>
	<p>
		<button type="submit">전송하기</button>
	</p>
</form>


</body>
</html>

 

form의 action을 통해 jsp을 실행

더보기

 

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	// 클라이언트가 서버로 보낸 정보의 문자 인코딩
	request.setCharacterEncoding("UTF-8");

	// 클라이언트가 서버로 보낸 정보 받기
	String name = request.getParameter("name");
	int age = Integer.parseInt(request.getParameter("age"));
	
	String state = age>= 19 ? "성인" : "미성년자";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h3>서버 - 결과</h3>

<p>이름 : <%=name%></p>
<p>나이 : <%=age%>, <span style="color: blue; font-weight: 700;"><%=state%></span> </p>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function send() {
	var f = document.myForm;
	
	if(! f.name.value){
		alert("이름을 입력하세요.");
		f.name.focus();
		return; 
	}
	
	if(! /^(\d)+$/.test(f.age.value)) {
		alert("나이는 숫자만 가능합니다.");
		f.age.focus();
		return;
	}
	
	// submit 기능이 없는 컨트롤에서 서버로 전송할 경우 submit() 함수를 호출한다.
	f.sumbit(); // 서버로 전송
}

</script>

</head>
<body>

<h3>일반 버튼 - 서버로 전송</h3>
<form action="request.jsp" name="myForm" method="post">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 나이 : <input type="text" name="age"></p>
	<p>
		<button type="button" onclick="send();">전송하기</button>
	</p>
</form>


</body>
</html>

 

 

element

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function send() {
	var f = document.myForm;
	var s = "";
	
	if(! f.name.value ){
		f.name.focus();
		return;
	}
	
	if(! f.age.value ){
		f.age.focus();
		return;
	}
	
	s = "<p>이름:"+f.name.value+"</p>";
	s += "<p>나이:"+f.age.value+"</p>";
	s += "<p>좋아하는 과목:";
	
	// 동일한 이름이 2개 이상이면 배열로 처리해야 한다.
	for(var i = 0; i<f.subject.length; i++) {
		if( f.subject[i].value ) {
			s += f.subject[i].value+" ";
		}
	}
	
	s += "</p>";
	
	document.getElementById("layout").innerHTML = s;
	
}

</script>

</head>
<body>

<form name="myForm">
	<p> 이름 : <input type="text" name="name"> </p>
	<p> 나이 : <input type="text" name="age" value="0"> </p>
	<p> 과목 :
		<input type="text" name="subject"><br>
		<input type="text" name="subject"><br>
		<input type="text" name="subject">
	</p>
	<p>
		<button type="button" onclick="send()">확인</button>
	</p>
</form>
<hr>

<div id="layout"></div>
	
</body>


</html>

 

select, option 요소

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
window.onload = function() {
	var f = document.myForm;
	// f.subject.value = "web"; // value 속성에 select 박스 중 선택할 option의 value를 주면 선택됨
	f.subject[2].selected = true; // subject[2] : subject에서 선택할 option의 위치	
};

function send() {
	var f = document.myForm;
	var s = "";
	
	if(! f.subject.value) { // 선택된 것이 없음
		alert("조하하는 과목 선택은 필수입니다.");
		return;
	}
	
	s = "<p>이름: "+f.name.value+"</p>";
	s += "<p>출신도: "+f.city.value+"</p>";
	s += "<p>가장 좋아하는 과목: "+f.subject.value+"</p>";
	
	for(var i=0; i<f.hobby.length; i++) {
		if(f.hobby[i].selected) {// 선택된 경우
			s += f.hobby[i].value+" ";
		}
	}
	
	s+="</p>";
	
	document.getElementById("layout").innerHTML = s;
}

</script>

</head>
<body>

<h3>select, option 요소</h3>

<form name="myForm">
<p> 이름 : <input type="text" name="name"> </p>
<p> 출신도 :
	<select name="city">
		<!-- 
			<option value=''>text</option>
			value : 서버로 전송되는 값(value 속성이 없으면 text가 서버로 전송)
			text : 눈에 보이는 값
		 -->
		<option>서울</option>
		<option selected="selected">경기</option>
		<option>인천</option>
		<option>기타</option>
	</select>
</p>

<p> 가장 좋아하는 과목 :
	<select name="subject">
		<option value="">::선택::</option>
		<option value="java">자바</option>
		<option value="oracle">오라클</option>
		<option value="web">웹</option>
	</select>
</p>

<p> 취미 :
	<select name="hobby" multiple="multiple" size="5">
		<option value="게임">게임하기</option>
		<option value="축구">축구하기</option>
		<option value="음악">음악듣기</option>
		<option value="영화">영화보기</option>
		<option value="수영">수영하기</option>
	</select>
</p>
<p>
	<button type="button" onclick="send()">확인</button>
</p>
</form>

<div id="layout"></div>

</body>
</html>

클래스(class)

- class는 객체를 생성하기 위한 템플릿이다.

- 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화한다.

- ES 2015(ECMAScript 6) 이전까지는 비슷한 종류의 객체를 만들어내기 위해 생성자를 사용했다.

- ES 2015(ECMAScript 6) 에서 도입된 클래스는 생성자의 기능을 대체한다. class 표현식을 사용하면, 생성자와 같은 기능을 하는 함수를 훨씬 더 깔끔한 문법으로 정의할 수 있다.

 

개요

- class는 "특별한 함수"이다.

- 함수를 함수 표현식과 함수 선언으로 정의할 수 있듯이, class도 class 표현식과 class 선언 두 가지 방법을 이용하여 정의할 수 있다.

- 클래스는 함수로 호출될 수 없다.

- 클래스 선언은 let과 const처럼 블록 스코프에 선언한다.

- 클래스의 메소드 안에서 super 키워드를 사용할 수 있다.

- 함수 선언과 클래스 선언의 중요한 차이점은 함수 선언의 경우 호이스팅이 일어나지만, 클래스 선언은 호이스팅이 일어나지 않는다.

 

※ 클래스는 함수, 객체가 아니다.

class Person {
	console.log('hello');
}

위 결과는 에러 : Unexpected token

 

class Person {
	prop1:1,
	prop2:2
}

위 결과는 에러 : Unexpected token

 

클래스 몸체

- 클래스 body는 중괄호 {}로 묶여 있는 안쪽 부분으로 메소드나 constructor와 같은 class 멤버를 정의한다.

- 클래스의 본문(body)은 strict mode에서 실행된다. 즉, 여기에 적힌 코드는 성능 향상을 위해 더 엄격한 문법이 적용된다.

 

Constructor(생성자)

- constructor 메소드는 class로 생성된 객체를 생성하고 초기화하기 위한 특수한 메소드이다.

- "constructor"라는 이름을 가진 특수한 메소드는 클래스 안에 한 개만 존재할 수 있다. 클래스에 여러 개의 constructor메소드가 존재하면 SyntaxError가 발생한다.

- constructor는 부모 클래스의 constructor를 호출하기 위해 super 키워드를 사용할 수 있다.

 

클래스 정의 : class 표현식

- class 표현식은 class를 정의하는 또 다른 방법이다.

- class 표현식은 이름을 가질 수도 있고, 갖지 않을 수도 있다.

- 이름을 가진 class표현식의 이름은 클래스 body의 loval scope에 한해 유효하다. 

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
// 클래스
class User {
	// 생성자 : 생성자는 클래스안에서 constructor 라는 이름으로 정의한다.
	constructor({name, age}) {
		this.name = name;
		this.age = age;
	}
	
	// 메소드를 만드는 문법 그대로 사용하면 메소드가 자동으로 User.prototype 에 저장된다.
	msg() {
		return '안녕하세요. 제 이름은 ' + this.name + '입니다.';
	}
}

const obj = new User({name:'호호호', age:20});
console.log( obj.msg() );

console.log( typeof User) // function
console.log( typeof User.prototype.constructor ); // function
console.log( typeof User.prototype.msg ); // function
console.log( obj instanceof User ); // true

</script>


</head>
<body>

<h3>클래스</h3>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
class User {
	add(x, y) {
		return x+y; // 프로퍼티가 없으므로 this를 쓰면 안된다.
	}
	
	subtract(x, y) {
		return x-y;
	}
}

const obj = new User();
console.log( obj.add(10, 5) );

</script>

</head>
<body>

<h3>클래스</h3>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
const methodName = 'sayName';

class User {
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}
	
	// 임의의 표현식을 []로 둘러쌓아 메소드 이름으로 사용	
	[methodName]() {
		return `안녕 나는 ${this.name}이야. `; // 템플릿 리터널
	}	
}

const obj = new User('나나나', 10);
console.log( obj.sayName() );
</script>

</head>
<body>

<h3>클래스</h3>

</body>
</html>

 

클래스의 getter 혹은 setter를 정의하고 싶을 때는 메소드 이름 앞에 get 또는 set을 붙여주면 된다.

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
class User {
	constructor() {
		this._name = "";
	}
	get name() {
		return this._name;
	}
	
	set name(newName) {
		this._name = newName;
	}
}

const obj = new User();
obj.name = '홍길동'; // 속성처럼 부름. 메소드를 프로퍼티처럼 사용
console.log( obj.name );


</script>

</head>
<body>

<h3>클래스 - getter, setter</h3>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
class Rect {
	constructor(height, width) {
		this.height = height;
		this.width = width;
	}
	
	// getter
	get area() {
		return this.calc();
	}
	
	// 메소드
	calc() {
		return this.height * this.width;
	}
}

var obj = new Rect(10, 5);
console.log( obj.area );
console.log( obj.calc() ); // 괄호가 있어야지 해당 메소드를 호출 



</script>

</head>
<body>

<h3>클래스</h3>

</body>
</html>

 

 

ex19 클래스 예제

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
/*
class Rect {
	// 생성자
	constructor(h, w) {
		this.height = h;
		this.width = w;
	}
}

var obj = new Rect(10, 5);
console.log(obj.height, obj.width);
*/

class Rect {
	// 메소드
	area(h, w) {
		this.height = h;
		this.width = w;
		return this.height * this.width; // 생성자뿐만 아니라 메소드에서도 속성 추가 가능
	}
}

var obj = new Rect();
var a = obj.area(5, 7);
console.log(a);
console.log(obj.height, obj.width);
console.log(obj);

</script>
</head>
<body>

<h3>클래스</h3>

</body>
</html>

 

클래스 - 상속 예제

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
class Car {
	constructor(name) {
		this.name = name;
	}
	
	speed() {
		console.log(`${this.name}은 시속 80 입니다.`);
	}
	
	color() {
		console.log(this.name +'은 검정색입니다.')
	}
}

class Taxi extends Car {
	constructor(name) {
		super(name); // 상위 클래스의 생성자 호출
	}
	
	speed() { // 자바에서 override
		super.speed(); // 상위 클래스의 메소드 호출
		console.log(this.name+'은 시속 100 입니다.')
	}
}

var obj = new Taxi('그랜저');
console.log(obj.name);
obj.speed();
obj.color();

</script>
</head>
<body>

<h3>클래스 - 상속</h3>

</body>
</html>

 

프로토타입(prototype) 객체란 ?

- 자바스크립트의 모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어 있으며, 객체 지향의 상속 개념과 같이 부모 객체의 프로퍼티 또는 메소드를 상속받아 사용할 수 있게 한다. 이러한 부모 객체를 프로토타입 객체 또는 프로토타입이라 한다.

- 프로토타입 객체는 생성자 함수에 의해 생성된 각각의 객체에 공유 프로퍼티를 제공하기 위해 사용한다.

 · 프로토타입은 어떤 객체의 상위(부모) 객체의 역할을 하는 객체로서 다른 객체에 공유 프로퍼티(메소드 포함)를 제공한다.

 · 프로토타입을 상속받은 하위(자식) 객체는 상위 객체의 프로퍼티를 자신의 프로퍼티처럼 자유롭게 사용할 수 있다.

- 자바스크립트는 프로토타입을 기반으로 상속을 구현하여 불필요한 중복을 제거한다.

 

_proto_ 접근자 프로퍼티

- 자바스크립트의 모든 객체는 은닉(private) 속성의 [ [Prototype] ] 이라는 내부 슬롯(internal slot)을 가진다.

- 객체가 생성될 때 객체 생성 방식에 따라 프로토타입이 결정되고 [ [Prototype] ]에 저장된다. 

- [ [Prototype] ]은 자신의 프로토타입이 되는 상위 객체를 가리킨다.

- [ [Prototype] ]은 _proto_속성이 참조하는 숨은 링크로 모든 객체는_proto_ 접근자 프로퍼티를 통해 자신의 프로토타입, 즉 [ [Prototype] ] 내부 슬롯에 간접적(직접 접근 불가)으로 접근할 수 있다.

- 접근자 프로퍼티(accessor property) : 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수, 즉 [[Get] ], [ [Set] ]프로퍼티 어트리뷰트로 구성된 프로퍼티이다.

- Object.prototype의 접근자 프로퍼티인 _proto_는 getter/setter 함수라고 부르는 접근자 함수를 통해 프로토타입을 취득하거나 할당한다.

- _proto_ 접근자 프로퍼티는 상속을 통해 사용된다. (_proto_ 프로퍼티는 자신의 부모 객체(프로토타입 객체)이다.

- _proto_ 접근자 프로퍼티를 코드 내에서 직접 사용하는 것은 권장하지 않는다. 

 

프로토 타입

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
var obj = { // 객체 리터널로 객체 생성
	name:'홍길동',
	score:90
};

console.log(obj.valueOf()); // obj 에는 valueOf가 없지만 동작함. valueOf()는 상위 객체에서 물려 받음
console.dir(obj);

console.log(obj.__proto__ === Object.prototype);
// __proto__ : 객체의 부모를 나타내는 프로토타입으로 부모에게 물려 받은 정보를 가지고 있음
// prototype : 자신의 프로토 타입 객체로 하위로 물려줄 프로토 타입 정보를 가지고 있음

// --------------------------------
function User(name) {
	this.name = name;
}

var u = new User('이자바'); // 객체를 생성

console.dir(User);
console.dir(u);

</script>

</head>
<body>

<h3>프로토 타입</h3>

</body>
</html>

 

 

객체에 프로퍼티나 메소드 추가. prototype 이용

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
// prototype 프로퍼티 : 생성자에 존재. 생성자로 생성되는 객체에 물려줄 프로퍼티와 메소드를 가지고 있음.

function User(name, age) {
	this.name = name;
	this.age = age
}

User.prototype.score = 80;
User.prototype.state = function() {
	return this.age>=19 ? '성인':'미성년자';
};

var obj = new User('자바', 20);
console.log(obj.name, obj.score, obj.state() ); // 자바 80 성인

var obj2 = new User('스프링', 17);
console.log(obj2.name, obj2.score, obj2.state() ); // 스프링 80 미성년자

// Date 내장객체에 weekday 라는 메소드를 추가하여 요일 출력
Date.prototype.weekday = function() {
	let week = ['일', '월', '화', '수', '목', '금', '토'];
	return week[this.getDay()];
}

var now = new Date();
console.log( now.weekday() ); // 시스템 요일

</script>
</head>
<body>

<h3>객체에 프로퍼티나 메소드 추가. prototype 이용</h3>

</body>
</html>

 

객체(Object)란 ?

- 객체는 JavaScript 언어만이 가지고 있는 특징을 기초로 이루는 자료형으로, 데이터를 저장하고 있는 프로퍼티(property) 및 프로퍼티에 저장된 데이터에 조작을 가할 수 있는 method의 집합으로 구성된다.

- 객체는 '이름(key) : 값(value)' 형태의 프로퍼티들을 저장하는 컨테이너이다. 기본 타입은 하나의 값만을 가지지만 참조 타입인 객체는 여러 개의 프로퍼ㅣ들을 포함할 수 있으며, 이러한 객체의 프로퍼티들은 기본 타입의 값을 포함하거나 다른 객체를 가리킬 수 있다. 

- null 과 undefined 를 제외한 모든 원시 타입도 객체로 취급된다. 이러한 원시 타입들에도 프로퍼티가 추가될 수 있고, 모두 객체로서의 특징을 갖는다. (숫자, 문자열, 배열, 함수, 정규 표현식 등)

- 객체를 사용할 때는 속성 (property) 이름을 이용해서 속성 값을 읽거나 쓸 수 있다.

- 자바스크립트에선, 실행 시점에 특정 객체에 속성을 추가하거나 제거할 수 있다.

 

프로토타입(prototype) 기반 언어

- 자바스크립트는 클래스 기반이 아닌 프로토타입(prototype)을 기반으로 하는 객체 기반 언어이다.

- 프로토타입 기반 언어는 프로토타입 객체라는 개념이 있으며, 새로운 객체의 초기 속성을 가져오는 템플릿(template)으로 사용되는 객체이다. 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들며, 생성된 객체는 또 다른 객체의 원혀이 될 수 있다.

- 프로토타입 언어는 클래스 없이(Class-less)객체를 생성할 수 있다. ECMAScript 6에서 클래스가 추가 되었다.

- 모든 객체는 객체를 만들거나 런타임에 고유한 속성을 지정할 수 있다.

- 모든 객체를 다른 객체의 프로토타입으로 연결하여 두 번째 객체가 첫 번째 객체의 속성을 공유할 수 있다.

- 프로토 타입 객체를 참조하는 prototype 속성과 객체 멤버인 _proto_ 속성이 참조하는 숨은 링크가 있다.

_proto_ : 상위에서 물려 받은 객체의 프로토타입에 대한 정보(prototype link)

prototype : 자신의 프로토타입 객체로, 하위로 물려줄 프로토 타입의 정보(prototype object)

 

특징

- 모든 객체는 다른 객체로부터 상속을 받는다.

- 생성자 함수를 이용하여 객체 세트를 정의하고 생성할 수 있다.

- class와 마찬가지로 new 연산자로 하나의 객체(인스턴스)를 생성할 수 있다. 

- 하나의 객체를 생성자 함수와 결합된 프로토타입에 할당함으로써 객체의 계층구조를 생성한다.

- 프로토타입 체인에 따라 속성을 상속받는다.

- 생성자 함수 혹은 포로토타입은 초기 속성들을 명시한다. 개별 객체 혹은 전체 객체 세트에 동적으로 속성을 추가, 삭제할 수 있다.

 

 

객체생성 - 객체 리터널을 이용한 객체 생성

더보기

객체 리터널(이니셜라이저)를 이용한 객체 생성

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
// 객체 리터널(이니셜라이저)를 이용한 객체 생성
var obj = {name:'홍길동', age:20}; // 프로퍼티이름:값, 프로퍼티명은 문자열만 가능
// var obj = {'name':'홍길동', 'age':20}; // 가능

console.log( typeof obj ); // "object"
console.log( obj );
console.dir( obj );

// 객체 속성 값 확인
console.log( obj.name ); // 홍길동

// 객체 속성 값 변경
obj.name = '김자바';
console.log( obj.name ); // 김자바

var s;
s = obj.age >= 19 ? obj.name +"님은 성인 입니다." : obj.name+"님은 성인이 아닙니다.";
console.log( s );

obj.Age = 22; // 대소문자가 다르면 에러가 나오지 않고 새로운 속성이 추가된다.
console.log( obj.age ); // 20

console.dir( obj );

// 객체 리터널(이니셜라이저)를 이용한 객체 생성 - 2
var obj2 = { }; // 빈 객체
console.log( typeof obj2 ); // object

// 실행시 동적으로 속성 추가
obj2.subject = "자바";
console.log( obj2 );
console.log( obj2.subject );

// 객체 리터널(이니셜라이저)를 이용한 객체 생성 - 3
var obj3 = {
	name : '홍길동',
	age : 20,
	state : function() {
		return this.age >= 19 ? '성인' : '미성년자'; // this 생략불가
	},
	msg : function() {
		var s = `${this.name}님은 ${this.state()} 입니다.`; // 템플릿 리터널
		console.log(s);
	}
};

console.log( obj3 );
obj3.msg();

</script>

</head>
<body>

<h3>객체 만들기</h3>

</body>
</html>

 

객체 이니셜라이저(object initializer) 를 이용한 객체 생성

- 객체 이니셜라이저를 이용하여 객체를 생성할 수 있으며, 리터럴 표기에 의한 객체(literal notation, 객체 리터널) 생성이라고도 한다.

- 객체 이니셜라이저는 여러 가지 프로퍼티를 가진 객체를 쉽게 정의할 수 있도록 디자인된 표기법이다.

- 중괄호 { } 를 이용해서 객체를 생성하며, 중괄호 { } 안에 아무것도 적지 않은 경우는 빈 객체가 된다.

- 중괄호 { } 안에 '프로퍼티 이름:프로퍼티 값' 형태로 표기하면, 해당 프로퍼티가 추가된 객체를 생성할 수 있다.

- 객체의 프로퍼티들이 객체의 특징을 규정한다. 

 

 

생성자 함수를 이용한 객체 생성

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
// 생성자 함수를 이용한 객체 생성

// 생성자 함수 작성 - 생성자는 대문자로 시작한다.
function User(name, age) {
	this.name = name;
	this.age = age;
	
	this.state = function() {
		return this.age >= 19 ? "성인":"미성년자";
	}
	
	this.msg = function() {
		var s = this.name + "님은 " +this.state()+"입니다.";
		console.log(s);
	}
}
// 생성자 함수를 이용한 객체 생성
var obj = new User('홍길동', 20);
console.log(obj.name);
obj.msg();

// Object.create()메소드를 이용한 객체 생성
var Book = {
	subject:'자바',
	msg: function() {
		return '좋아하는 과목은 '+this.subject+'입니다.';
	}
};

var b1 = Object.create(Book);
var b2 = Object.create(Book);
b1.subject = 'HTML';
b2.subject = 'CSS';

console.log(Book.msg());
console.log(b1.msg());
console.log(b2.msg());


</script>
</head>
<body>

<h3>객체 생성</h3>

</body>
</html>

생성자 함수를 이용한 객체 생성 특징

- 객체 타입을 정의하는 생성자 함수명의 첫 글자는 일반적으로 대문자로 시작한다.

- 생성자에 매개변수가 없으면 생성자를 호출할 때 전달인자 목록과 괄호를 생략할 수 있다.  var o = new Object;

- 생성자를 호출하면 생성자의 프로토타입 속성을 상속받은 새로운 빈 객체가 생성된다.  생성자 함수는 객체를 초기화하고 새로 생성된 이 객체는 호출 컨텍스트로 사용된다.

- 생성자는 새로 생성된 객체를 this 키워드로 참조할 수 있다.

- 생성자 함수는 보통 return 키워드를 사용하지 않는다. 일반적으로 생성자 함수는 새 객체를 초기화하고 생성자 함수 몸체의 끝에 이르면 암시적으로 그 객체를 반환한다. 

- 만약 생성자가 return 문을 사용하여 명시적으로 어떤 객체를 반환하면, 반환된 객체가 생성자 호출 표현식의 값이 되며, 생성자가 반환 값 없이 return 구문만을 사용하거나 원시 형식 값을 반환하면, 그 반환 값은 무시되고 새로 생성된 객체가 호출 표현식 값으로 사용된다. 

 

this 키워드

- 자바스크립트에서 함수를 호출할 때 기존 매개변수로 전달되는 인자 값에 더해 arguments 객체 및 this 인자가 함수 내부로 암시적으로 전달된다. 

- 현재 객체를 참조할 때 this키워드 사용하며, 일반적으로 this는 메소드에서 호출하는 객체를 참조한다.

- 객체의 프로퍼티는 점(.)이나 괄호([])로 접근할 수 있다.

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
// 객체의 메소드를 호출할 때 메소드 내부 코드에서 사용한 this : 해당 메소드를 호출한 객체
var obj = { // 객체 생성. 일회성. 주로 속성값 보존을 위해 사용
		name : '김자바',
		msg : function() {
			console.dir(this);
			console.log(this.name); // this는 msg() 메소드를 호출한 객체
		}
};

obj.msg();

// 생성자 함수를 호출할 때의 this : 새로 생성되는 객체
function Test(arg) {
	this.name = arg;
	this.getName = function() {
		return this.name;
	};
}

var obj2 = new Test('자바');
console.log( obj2.getName() );

// 함수를 호출할 때의 this
var userName = '스프링'; // 전역 변수. 전역변수는 자동으로 window의 속성이 된다.
// console.log(userName); // 스프링
console.log(window.userName); // 스프링

// sayUser()를 호출할 때 this는 전역 객체(window)에 바인딩
var sayUser = function() {
	console.log( this.userName, userName, window.userName );
}
sayUser();

</script>


</head>
<body>

<h3>객체- this</h3>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
// 객체의 메소드를 호출할 때 메소드 내부 코드에서 사용한 this : 해당 메소드를 호출한 객체
var obj = { // 객체 생성. 일회성. 주로 속성값 보존을 위해 사용
		name : '김자바',
		msg : function() {
			console.dir(this);
			console.log(this.name); // this는 msg() 메소드를 호출한 객체
		}
};

obj.msg();

// 생성자 함수를 호출할 때의 this : 새로 생성되는 객체
function Test(arg) {
	this.name = arg;
	this.getName = function() {
		return this.name;
	};
}

var obj2 = new Test('자바');
console.log( obj2.getName() );

// 함수를 호출할 때의 this
var userName = '스프링'; // 전역 변수. 전역변수는 자동으로 window의 속성이 된다.
// console.log(userName); // 스프링
console.log(window.userName); // 스프링

// sayUser()를 호출할 때 this는 전역 객체(window)에 바인딩
var sayUser = function() {
	console.log( this.userName, userName, window.userName );
}
sayUser();

</script>


</head>
<body>

<h3>객체- this</h3>

</body>
</html>

 

 

 

- this 바인딩

 · 객체의 메소드를 호출할 때 this : 해당 메소드를 호출한 객체

 · 함수를 호출할 때 this : 전역 객체

 · 생성자 함수를 호출할 때 this : 새로 생성되는 객체

 

 

form 요소의 이벤트 핸들러에서의 this : 이벤트를 발생시킨 객체

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function send() { // document 는 body라고 생각하면 됨
	var f = document.myForm;
	var name = f.name.value;
	var kor = f.kor.value;
	var eng = f.eng.value;
	var mat = f.mat.value;
	
	alert(name + ":" + kor + ":" + eng + ":" + mat);
}

function validate(obj) {
/*	
	if(! /^(\d){1,3}$/.test(obj.value) ) {
		obj.focus;
		return;
	}
*/
	if(isNaN(obj.value) || parseInt(obj.value) < 0 || parseInt(obj.value) > 100) {
		alert("점수는 0~100 사이만 가능합니다.");
		obj.focus();
		return;
	}
}

</script>

</head>
<body>

<h3>form 요소의 이벤트 핸들러에서의 this : 이벤트를 발생시킨 객체 자기 자신</h3>
<form name="myForm">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 국어 : <input type="text" name="kor" onchange="validate(this);"></p>
	<p> 영어 : <input type="text" name="eng" onchange="validate(this);"></p>
	<p> 수학 : <input type="text" name="mat" onchange="validate(this);"></p>
	<p>
		<button type="button" onclick="send()">확인</button>
	</p>
</form>

</body>
</html>

 

form 요소의 안에서의 this.form : 현재 객체의 부모 form을 나타냄

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
function send(f) { // f는 document.myForm 을 말함
	var name = f.name.value;
	var kor = f.kor.value;
	var eng = f.eng.value;
	var mat = f.mat.value;
	
	alert(name + ":" + kor + ":" + eng + ":" + mat);
}


</script>

</head>
<body>

<h3>form 요소의 안에서의 this.form : 현재 객체의 부모 form을 나타냄</h3>
<form name="myForm">
	<p> 이름 : <input type="text" name="name"></p>
	<p> 국어 : <input type="text" name="kor"></p>
	<p> 영어 : <input type="text" name="eng"></p>
	<p> 수학 : <input type="text" name="mat"></p>
	<p>
		<button type="button" onclick="send(this.form)">확인</button>
	</p>
</form>

</body>
</html>

 

객체 프로퍼티

- 객체의 프로퍼티는 객체의 특징을 규정한다.

- 프로퍼티 이름은 유효한 자바스크립트 문자열이거나 문자열로 변환이 가능한 어떤 것 또는 빈 문자열도 가능하다.

- 자바스크립트 식별자(identifier)로 적합하지 않으면(하이픈, 빈칸을 포함, 숫자로 시작하는 이름 등), 대괄호를 이용한 표기법으로만 접근이 가능하다.

- 프로퍼티에 접근해서 객체의 기존 프로퍼티 값을 갱신할 수 있다.

- 객체가 생성된 후에도 동적으로 프로퍼티를 생성해서 해당 객체에 추가가 가능하다.

- 상속 받지 않은 객체의 프로퍼티는 delete 연산자를 이용해 삭제하며, 삭제된 속성은 undefined로 설정한다.

delete objectName.propertyName;

- 객체 프로퍼티 접근은 도트 표기법, 대괄호 표기법이 있다.

ec) objectName.propertyName, objectName["propertyName"]

 

객체 - 프로퍼티 동적 추가

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
var obj = {
	name:'자바',
	city:'서울'
};

console.log(obj.name);
console.log(obj.city);
console.log(obj.age); // 없는 속성은 undefined. 에러가 아님

// 동적 속성 추가
obj.age = 10;
console.log(obj.age);

// 속성 제거
delete obj.city;
console.log(obj.city);

</script>
</head>
<body>

<h3>객체 - 프로퍼티 동적 추가</h3>

</body>
</html>

 

객체 프로퍼티 접근 및 나열

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
var obj = {
	name:'이자바',
	age:20,
	msg: function() {
		return this.age>=19? '성인':'미성년자';
	}
};

// 객체 속성 접근
console.log(obj.name); // 도트 표기법 접근
console.log(obj['name']); // 대괄호 표기법으로 접근

// 메소드 접근
console.log(obj.msg());

// 객체의 프로퍼티 나열
for(var ob in obj) { // ob : 프로퍼티이름
	console.log(ob, obj[ob]);
}

console.log('name' in obj); // true. 객체에 속성이 존재하는지 확인
console.log('subject' in obj); // false

// console.log(obj.name);
// 간단한 표현
with(obj) {
	console.log(name);
	console.log(age);
}

</script>
</head>
<body>

<h3>객체 - 프로퍼티 접근 및 나열</h3>

</body>
</html>

 

정적 메소드(static method)

- 생성자의 속성에 직접 지정된 메소드를 정적 메소드(static method)라고 한다.

- Number.isNaN, Object.getPropertyOf 등의 함수들은 모두 정적 메소드이다.

- 정적 메소드는 특정 인스턴스에 대한 작업이 아닌, 해당 생성자와 관련된 일반적인 작업을 정의할 때 사용된다. 

 

생성자 함수에 추가하는 프로퍼티나 메소드

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
/*
 - 생성자 함수에 추가하는 프로퍼티나 메소드 : 프로토타입에 추가하므로 생성자를 통해 생성된 모든 다른 객체에 적용
 - 프로토타입
	객체는 부모 객체의 프로퍼티나 메소드를 상속 받아 사용할 수 있으며, 
	이러한 부모 객체를 프로토 타입 객체 또는 프로토타입이라 함 
*/ 
function User(name) {
	this.name = name;
	this.age = 20; // 기본값을 가질 수 있음
	this.state = function() {
		return this.age >= 19 ? '성인':'미성년자';
	};
}

console.dir(User);

var obj = new User('홍길동');
console.log(obj.name, obj.state() );

</script>

</head>
<body>

<h3>생성자 함수에 추가하는 프로퍼티나 메소드</h3>

</body>
</html>

 

정적 메소드

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<script type="text/javascript">
// 정적 메소드 : 생성자에 직접 지정된 메소드
function User(name) {
	this.name=name;
	this.getName = function() {
		return this.name;
	};
}

// 클래스 안에 정적 메소드 추가
// 정적 메소드
User.state = function(age) {
	return age>=19? '성인':'미성년자'; 
	// this가 있을 수 없음. 객체 생성과 상관 없음. this는 정적메소드와 상관없음
};

console.log(User.state(30));
// console.log(User.getName()); // 에러. 정적 메소드가 아님. 객체를 생성해서 호출해야함

var obj = new User('하하하'); // 메모리할당
console.log(obj.getName());

</script>


</head>
<body>

<h3>정적 메소드</h3>

</body>
</html>

 

JSON 객체

- JSON 객체는 JavaScript Object Notation(JSON)을 분석하거나 값을 JSON으로 변환하는 정적 메소드를 가지고 있다.

- JSON을 직접 호출하거나 인스턴스를 생성할 수 없다.

 

정적 메소드

- JSON.parse()

- JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성한다.

(JSON 문자열을 JSON 객체로 변환 한다.)

 

- JSON.stringify()

- JavaScript 값이나 객체를 JSON 문자열로 변환( JSON 객체를 JSON 문자열로 변환한다.)

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
// JSON 문자열을 자바스크립트 객체로 변환
var s = '{"name":"홍길동","subject":"자바","score":95}'; // JSON 문자열
// 어떤 브라우저는 JSON property 를 홑따옴표로 하면 못 읽는 곳이 있음. 
// 따라서 위처럼 홑따옴표를 먼저 쓰고 프로퍼티는 쌍따옴표를 쓸 것!
var obj = JSON.parse(s); // JSON 문자열을 분석하여 자바스크립트 객체 생성
console.log(obj.name, obj.subject, obj.score );
// 숫자, true, false는 쌍따옴표로 안감싸도 됨
// 자바스크립트 객체를 JSON 문자열로 변환
var obj2 = {
	name:'김자바', 
	age:20, 
	subject:'HTML'
};

var s2 = JSON.stringify(obj2); // 자바스크립트 객체를 JSON 문자열로 변환
console.log(s2);

</script>

</head>
<body>

<h3>JSON</h3>

</body>
</html>

+ Recent posts