자바스크립트(JavaScript) 기초강좌 - 3장. JavaScript 객체


자바스크립트(JavaScript) 기초강좌 - 3장. JavaScript 객체

3장. JavaScript 객체

3.1) 자바스크립트 객체 종류

자바스크립트에는 수많은 객체가 이미 정의되어 있다. 이 객체들은 크게 두 가지 Web Browser와 관련 있는 Browser객체와 자바스크립트 자체에 내장된 객체로 나누어 볼 수 있다. 또한 이 두가지 객체모형 이외에 사용자가 객체를 직접 정의하여 사용할 수 있다.

 

I. Browser 객체

* 브라우저 객체는 브라우저 화면에 나타나는 모든 요소들을 포함하는 것으로 트리 구조로 되어 있다. Window라는 최상위 객체에서 파생된 수 많은 하위 객체를 포함하고 있으며 각각의 하위 객체들은 계층 구조에 의해 정의되어 있으며 접근할 수 있다.

* 브라우저 객체에는 Window, Document, Frame, History, Location, Form, Image, Link, Radio, Text, Checkbox, Select, Textarea, Navigator등이 있다.

* Netscape의 객체모형과 Explorer의 객체 모형은 약간 다르다.

 

II. 내장객체

* 자바스크립트 내장객체에는 Date, Math, String, Array등이 있다.

* Math 객체는 static객체이므로 new를 이용하여 생성하지 않는다. 수학계산이나 난수 등을 얻기 위해 사용되는 객체이다.

* 다른 내장 객체들은 별도의 설명을 참조하기 바란다.

 

 

III. 사용자 정의 객체

* 자바스크립트에는 많은 객체들이 내장되어 있지만 보다 효율적인 작업을 위해 객체를 직접 정의해서 사용하기도 한다. 사용자 정의객체는 생성자 함수(Constructor)와 new keyword를 이용하여 만든다.

 

3.2) Browser 객체

3.2.1) 윈도우

Window는 JavaScript의 Browser객체로 웹서핑(Web Surfing)을 하다 보면 흔히 만나게 되는 것이 광고나 Event, 여러 가지 공지사항 등을 작은 창에 띄우는 것이다.

자바스크립트를 이용하면 이와같은 Window들을 다양한 방법으로 제어할 수 있다.

 

I. Window Open

[형식]

winObject = window.open("url", "name", "options");

 

* winObject는 open된 window를 가리키는 reference변수이다.

* url (반드시 있어야 한다)

새로 만들어진 window에 나타날 web문서의 URL을 적는다. 적당한 url이 없을 경우 ""로 표시한다.

* name (반드시 있어야 한다)

새로 만들어진 window의 이름을 지정한다. 적당한 name을 붙이지 않으려면 ""로 표시하면 된다. name위치에 입력한 이름은 <FORM>이나 <A>태그에서 사용하는 Target속성으로 연결할 수 있다.

* options (생략가능하며 생략하는 경우 default값이 적용된다)

1. menubar : window의 menubar표시 여부 (yes/no or 1/0)

2. toolbar : window의 toolbar표시 여부 (yes/no or 1/0)

3. location : window의 location box표시여부 (yes/no or 1/0)

4. directories : window의 directory button들의 출력여부 (yes/no or 1/0)

5. status : window의 상태표시줄 표시 여부 (yes/no or 1/0)

6. scrollbars : window의 가로, 세로 scrollbar표시 여부 (yes/no or 1/0)

7. resizable : window의 크기가 조절 될 수 있는지 결정 (yes/no or 1/0)

8. width : Display될 window의 너비 결정 (단위 pixel)

9. height : Display될 window의 높이 결정 (단위 pixel)

10. left : Display될 window의 좌측 상단의 x좌표 (단위 pixel)

11. top : Display될 window의 좌측 상단의 x좌표 (단위 pixel)

 

II. Window Close

[형식]

window.close();

 

* window를 종료할 때는 반드시 Window가 open이 되었는지 check한 다음 close하도록 한다.

 

III. 예제

다음 예제를 실행하여 'Window열기'를 Click하면 300 X 200크기의 작은 Window가 화면(50,50)위치에 open된다.

'Window닫기'를 누르면 현재 open된 작은 window를 닫느다.

closeWin()에서 s_win.close()를 사용하지 않고 window.close를 사용하면 Link가 있는 Parent Window를 종료할 것인지 묻는 Confirm Box가 뜬다.

 

<HTML>

<HEAD>

<SCRIPT Language="JavaScript">

function openWin()

{

s_win = window.open( "", "small", "width=300,height=200,left=50,top=50");

}

 

function closeWin()

{

if ( s_win != null )

s_win.close();

}

</SCRIPT>

</HEAD>

 

<BODY>

<H3><A HREF="javascript:openWin()">Window 열기</A></H3>

<H3><A HREF="javascript:closeWin()">Window 닫기</A></H3>

</BODY>

</HTML>

 

3.2.2) Document

Document는 window의 하위 객체로 document는 window.document를 의미한다. 주로 최상위 객체인 window는 생략하고 사용한다.

 

I. Document Open

[형식]

Window명.document.open();

 

* document.open()은 윈도우에 문서를 출력할 준비를 하도록 명령하는 것이다.

* Window Open시 document.open()은 생략해도 무관하다. 그 이유는 document.write()가 사용되면 브라우저는 자동적으로 document.open()메소드를 실행하기 때문이다.

 

II. Document Close

[형식]

Window명.document.close();

 

* 문서를 열고 무엇인가를 쓴 다음 문서를 닫아 줄때 사용한다.

* document.open()처럼 대부분 생략하고 사용하지만 현재 Window가 아닌 임의의 다른 Window에 무엇인가를 출력할 경우는 반드시 document.close()를 적어 주어야 한다. 그렇지 않으면 브라우저는 문자열의 출력이 완료되지 않았다고 판단하기 때문에 제대로 된 결과가 나타나지 않을 수도 있다.

 

III. Document Write

[형식]

Window명.document.write(); or

Window명.document.writeln();

 

 

* Open한 문서에 무엇인가를 Write할 때 사용한다.

* document.write()는 줄바꿈을 하지 않으며, document.writeln()은 줄바꿈을 한다.

 

III. Document Write

[형식]

Window명.document.write(); or

Window명.document.writeln();

 

* Open한 문서에 무엇인가를 Write할 때 사용한다.

* document.write()는 줄바꿈을 하지 않으며, document.writeln()은 줄바꿈을 한다.

 

IV. Document Clear

[형식]

Window명.document.clear();

 

* Document를 clear할 때 사용한다.

* window를 clear하고자 할 경우 open(), clear(), close()순으로 해야 한다.

 

V. 예제

<HTML>

<HEAD>

<SCRIPT Language="JavaScript">

var winObj = null;

 

function openWin()

{

winObj = window.open("", "", "width=300,height=250");

}

 

function closeWin()

{

if ( winObj != null )

{

winObj.close();

winObj = null;

}

}

 

function writeWin()

{

if ( winObj != null )

{

winObj.document.open();

winObj.document.writeln("<HTML><HEAD>");

winObj.document.writeln("<TITLE>Document</TITLE>");

winObj.document.writeln("</HEAD><BODY><CENTER>");

winObj.document.writeln("<H3>안녕하세요!</H3>");

winObj.document.writeln("</CENTER></BODY></HTML>");

winObj.document.close();

}

}

 

function clearWin()

{

if ( winObj != null )

{

winObj.document.open();

winObj.document.clear();

winObj.document.close();

}

}

</SCRIPT>

</HEAD>

 

<BODY>

<INPUT TYPE=button VALUE="열기" onClick="openWin();"><BR>

<INPUT TYPE=button VALUE="쓰기" onClick="writeWin();"><BR>

<INPUT TYPE=button VALUE="지우기" onClick="clearWin();"><BR>

<INPUT TYPE=button VALUE="닫기" onClick="closeWin();"><BR>

</BODY>

 

</HTML>

 

3.2.3) Frame

* Frame이란 하나의 Browser안에 독립적으로 존재하는 다수의 Frame을 표현할 수 있는 Window의 특별한 유형을 말한다.

* 각각의 Frame들은 자신만의 URL을 가지며, 모두 같은 Window내에 존재한다.

* Frame은 최소 3개의 File로 구성된다.

각각의 Frame을 포함하는 Parent가 존재한다.

* Parent Window에서 Child Frame으로의 이동

[형식]

framName.location.href="URL"

단순히 Child Frame의 이름을 적어 주는 식으로 접근한다.

 

* Child Frame에서 Child Frame으로의 이동

[형식]

parent.frameName.location.href="URL"

Child Frame에서 Child Frame으로 바로 접근할 수 없으므로 Parent Frame을 거쳐 접근해야 한다.

 

* Child Frame에서 Parent Window로의 이동

[형식]

parent.location.href="URL"

Child Frame에서 Parent Window로 접근한다는 것은 Frame을 없애는 것과 같다. Window객체의 속성인 parent를 이용하여 부모 윈도우로 접근할 수 있다.

 

 

 

 

 

3.2.4) History

Window의 하위객체로 History가 있다. 이것은 사용자가 방문했던 사이트의 목록을 기록해 둔 것이라고 할 수 있다.

Browser의 도구 모음에서 [뒤로], [앞으로] 버튼을 눌렀을 때 브라우저는 History목록을 이용해서 앞으로 혹은 뒤로 이동하게 된다.

자바스크립트를 이용하면 도구 모음에서 [뒤로], [앞으로]버튼을 눌렀을 때와 같은 효과를 얻을 수 있다.

 

* [형식]

window는 생략 가능하다.

 

window.history.go()

history객체의 go(숫자) 메소드는 숫자만큼 페이지를 앞뒤로 이동시켜 준다.

 

window.history.forward()

history객체의 go(1)과 같은 역할을 한다.

 

window.history.back()

history객체의 go(-1)과 같은 역할을 한다.

 

* [예제]

<HTML>

<BODY>

<FORM>

<INPUT TYPE="button" onClick="history.back()" VALUE="뒤로">

<INPUT TYPE="button" onClick="history.forward()" VALUE="앞으로">

<INPUT TYPE="button" onClick="history.go(-2)" VALUE="2Page뒤로">

</FORM>

</BODY>

</HTML>

 

3.3) 자바스크립트 내장 객체

3.3.1) Date 객체

* Date객체를 사용하면 날짜와 시간을 표시하거나 설정할 수 있다. 자바스크립트에서는 그리니치 표준시(GMT)로 1970년 1월 1일 00:00:00을 사용한다.

* 사용자 컴퓨터의 현재 날짜와 시간을 자동으로 지정할 수 있다.

예) 객체이름 = new Date()

 

* 특정 날짜와 시간을 지정할 수 있다.

예) 객체이름 = new Date("month, day, year, hh:mm:ss")

객체이름 = new Date(year, month, day)

객체이름 = new Date(year, month, day, hours, minutes, seconds)

 

* Date객체의 Method

 

Method 

설명

getYear()/setYear() 

년도 표시/설정

getMonth()/setMonth() 

월 표시/설정 0(1월) ~ 11(12월)

getDate()/setDate() 

일 표시/설정 (1 ~ 31)

getDay()/setDay() 

요일 표시/설정 0(일) ~ 6(토)

getHours()/setHours() 

0 ~ 23시를 표시/설정

getMinute()/setMinute() 

0 ~ 59분을 표시/설정

getSecond()/setSecond() 

0 ~ 59초를 표시/설정

getFullYear()/setFullYear() 

년도 수를 4자리로 표시/설정

toStrings() 

날짜와 시간을 문자열로 변환

toGMTString() 

날짜와 시간을 GMT 문자열로 변환

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.3.2) String 객체

* String객체는 글자 모양을 지정하거나 문자열을 처리하기 위해 사용한다.

* [속성]

length : 문자열의 길이

 

* String객체의 Method

Method 

설명

charAt(n) 

지정된 위치의 문자를 반환 : n은 index번호

charCodeAt(n) 

지정된 위치에 있는 문자의 Unicode번호를 반환

concat(문자열)

두개의 문자열을 병합

indexOf(문자열)

왼쪽부터 검색해서 지정된 문자열의 위치를 반환

lastIndexOf(문자열)

오른쪽부터 검색해서 지정된 문자열의 위치를 반환

split(분리자)

분리자를 기준으로 문자열을 분리

substring(A, B) 

A에서 시작해서 B전까지의 문자열 반환

substr(A, n) 

A에서 시작해서 n만큼의 문자열 반환

3.3.3) Array 객체

* 배열의 이름과 index 번호로 접근한다.

* [속성]

length : 배열의 길이

* Array 객체의 Method

Method 

설명

join(문자열)

배열의 값들을 결합해서 하나의 문자열로 만든다.

reverse() 

배열의 순서를 반대로 바꿔 준다.

sort(비교함수)

비교함수를 생략하면 오름차순 정렬

slice(start, end) 

배열의 일부를 선택해서 새로운 배열생성 예) a.slice(0,2) --> a[0], a[1]을 의미한다. (end의 index는 포함되지 않는다.)

concat(배열이름)

두개의 배열을 concatenation해서 하나의 배열로 만든다. 예) a.concat(b) --> 배열 a와 배열 b가 합해져서 새로운 배열 생성

3.4) 사용자 정의 객체

사용자 정의객체는 생성자 함수(Constructor)와 new keyword를 이용하여 다음과 같은 방식으로 만든다.

 

I. Parameter가 없는 User Object

[형식]

function 함수명()

{

this.Property1;

this.Property2;

}

 

사용자 정의객체이름 = new 함수명();

 

 

* 예제

<HTML>

<HEAD>

<SCRIPT>

function member()

{

this.name;

this.phone;

this.address;

}

 

mem = new member();

 

mem.name = "자바누리";

mem.age = "123-4567";

mem.address = "서울 강남구 대치동";

 

document.write("<H3>회원명 : " + mem.name + "</H3>");

document.write("<H3>전화번호 : " + mem.age + "</H3>");

document.write("<H3>주소 : " + mem.address + "</H3>");

</SCRIPT>

</HEAD>

</HTML>

 

II. Parameter가 있는 User Object

* [형식]

function 함수명(parameter1, parameter2...)

{

this.Property1 = parameter1;

this.Property2 = parameter2;

}

 

사용자 정의객체이름 = new 함수명( argument1, argument2, ..);

* 예제

<HTML>

<HEAD>

<SCRIPT>

function member(name, phone, addr)

{

this.name = name;

this.phone = phone;

this.address = addr;

}

 

mem = new member("자바누리", "123-4567", "서울 강남구 대치동");

 

document.write("<H3>회원명 : " + mem.name + "</H3>");

document.write("<H3>전화번호 : " + mem.age + "</H3>");

document.write("<H3>주소 : " + mem.address + "</H3>");

</SCRIPT>

</HEAD>

</HTML>

 

III. 사용자 정의객체에서 Method 정의

* [형식]

function 함수명(parameter1, parameter2...)

{

this.Property1 = parameter1;

this.Property2 = parameter2;

this.Method1 = 메소드명;

...

}

 

function 메소드명()

{

}

 

사용자 정의객체이름 = new 함수명( argument1, argument2, ..);

 

* 예제

<HTML>

<HEAD>

<SCRIPT>

function member(name, phone, addr)

{

this.name = name;

this.phone = phone;

this.address = addr;

 

this.showmember = show;

}

 

function show()

{

document.write("<H3>회원명 : " + mem.name + "</H3>");

document.write("<H3>전화번호 : " + mem.age + "</H3>");

document.write("<H3>주소 : " + mem.address + "</H3>");

}

 

mem = new member("자바누리", "123-4567", "서울 강남구 대치동");

 

mem.showmember();

</SCRIPT>

</HEAD>

</HTML>

이미지 맵

'IT Computer Utility/ETC' 카테고리의 다른 글

이전 글 다음 글