SlideShare a Scribd company logo
HR Kwon (hungrok@hanmail.net , khr2@samsung.com)
IT 강의자료
Java Script 핵심개념 (Core Concepts)
1
머리글
 HTML5 의 대중화 와 함께 Java Script 는 단순히 페이지를 동적으로 만든다는 초기 적용범위 에서 벗어나,
진정한 Web Application 을 위한 도구로 활용성이 증대되고 있다.
C 와 Java 를 경험해본 Software 개발자 이면 비슷한 것으로 간주하여 JS 가 지닌 핵심적인 개념을 충분한 이해없이
사용 할 것으로 짐작하여 본다.
원서로 된 여러 훌륭한 책 들이 있지만,
공부하면서 이해한 핵심적인 부분을 원 자료의 일부 인용과 병행하여 필요한 분 들과 공유 하고자 한다.
2013년 12월, Hungrok Kwon
 목차
. What is Java Script
. HTML5
. Java VS Java Script
. 변수
. 객체
. 함수일반
. 함수 – 객체화 및 상속
. 함수 - CLOSUE
. Execution Context Stack
. 디자인 Patterns
. 이벤트
. Library
Edition
1.0 2013.12
1.1 2014.07
1.2 2014.12
1.3 2015.05
2
What is Java Script
 Web 의 3요소 : HTML document, CSS, JS
 Web 페이지를 동적으로 만들고자 일련의 행위를 진행하기 위한 MVC (Model-data, View, Controller) 모델이다
< Tag , Element, Object >
. Tag 란 각 element 의 대표 속성을 지칭한다 (예. 사람, 호랑이, 비둘기,,,)
. Element 란 Tag 로 정의된 대표 속성을 지닌 개별 자 를 지칭한다 (예.사람-홍길동, 사람-이순신,,)
. 각 Element 는 문서내의 독립된 객체이다
. Node 란 객체 간의 상하 (부모 자식 형제) Tree 구조를 나타낸다
<표현적 Markup>
. 문서의 Layout 과 디자인 을 정의
. CSS3 features
- Transform/Transition/Animation
HTML5
Document
Style
Rule
Java
Script
Style
Effect
Event
Render Tree
Display
<구조적 Markup>
. Head {}, Body{}, Script{} , Style{}
. Tag (Element  Object)
. New 29 tags in HTML5
: canvas, audio, video
DOM
(Node Tree)
Effect
CSS
Document
3
What is Java Script
 일련의 행위란 특정한 객체 (Object) 와의 연동을 의미하며, Event 로 부터 시작한다
 객체는 크게 미리 만들어진 Object (Reference Object) 와 JS 가 스스로 생성한 객체 로 분류할 수 있다
 Reference Object 은 5가지로 분류할 수 있다 : * Element 와 Event 는 실제 적으로는 Window 하부객체이다
 Embedded Object 은 표준에서 지원하지 않는 Object 으로서 browser 에 built-in 되거나 (window.objA) 혹은
Plug-in (<OBJECT> 과 <embed> 태그로 reference ) 하여 사용한다.
Reference
Objects
Java
Script
Create
Objects
Event
Internal Devices
Server
document
. Native embedded : Array, Object, Function, Date, Math,,,,
. Browser : Window, Navigator, Screen, History, Location
. Core DOM : Document, Element, Attribute, Event
. HTML DOM elements : each elements in document
. Others : Library, Embedded Objects (Plug-In)
. Object (일반객체)
. Function (함수객체)
. Others : String, Date, Array
IP (http)
document.write
Element.innerHTML
Data
Processing
GFX, Media,
console.log
4
What is Java Script
 즉, JS 는 특정 Object 의 Property 를 상황에 맞추어 변경 하고자 함이 목적이다
 JS 가 Reference Object 을 접근하기 위하여 해당 Object 을 지정하는 방법은 세가지 이다
1) DOM 이 지니고 있는 attribute 를 이용하여 찾아낸다 :
x = document.getElementById(“main”) / x.getElementsByTagName(“p”) / getElementsByClassName(“classcar”)
2) DOM 이 지니고 있는 Node List 를 이용하여 찾아낸다 : Parent, Child,,
3) Event.target 을 이용한다 (Event 객체의 target 이 해당 Object 을 지칭한다, event.targetElement)
 JS 에 의하여 Reference Object 은 동적으로 추가 가 가능하다
Reference
Objects
Java
Script
Event
< W3C 에서 규정해놓은 Object 이 지니는 Properties >
(1) Global Attributes : 공통적으로 지닌 것 (id, name, class, style,,,)
(2) Attributes : 각 tag 별 (value,,)
(3) Event Attributes : Event type 을 의미한다
(4) Methods : function(){}
* Attributes 는 실제 define 이 되기전까지는 객체에 존재하지 않는다
: JS 객체의 속성을 지니는 관계이며, 동적으로 생성된다 (이벤트 페이지 참조)
* style 은 CSS 가 관장하는 속성 값들이다 (이것을 통하여 CSS 를 effect 시킨다)
* value 는 특정한 element 들만 지닌다 (input)
Java
Script
Object 접근
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
function myFunction() {
var node = document.createElement("LI");
var textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
동적추가
5
What is Java Script
 Java Script 에 의한 Web 페이지를 동적으로 만드는 예
. Tag 에 의하여 페이지에서 element 는 정의되고, 모든 element 는 Java Script 가 reference 하는 객체로 된다
. 해당 Element 가 지닌 속성 (Attribute 라 한다) 중 event attribute 에 Event Listener 역할을 하는 Java Script 함수를 연결한다
. 해당객체에 Event 가 발생하며, JS 의 특정 함수가 호출 (Invoke or Activate) 된다
. Image Object 의 소스를 변경하거나 사이즈를 확대한다
Image
Object
< Attributes >
. ID, Name, Class
. onclick = myFunction() ;
Deliver the Event to JS
JS
Function
Button
Objects
< 원래 Attributes >
. ID, Name, Class
. Width, Height
. Source = URL-A
BROWSER
(WebKit)
Event
function myFunction (event)
{ ; }
Which
Object
Event
User Event
Change The Source as URL-B
6
What is Java Script
 Java Script 에서 CSS 객체를 접근하는 방법
Static code 이외에, 아래와 같이 동적으로 접근하는 두 가지 방법이 있다
(1) DOM 내의 특정 Element 객체 가 지닌 “style” attribute 를 통하여 접근 : element.style.display = block ;
(2) Style Tag (<style>) 가 지닌 style 객체를 통하여 접근
* document 가 지니는 default CSS 객체에 의하여 특별한 지정이 없이 style 은 적용된다
(1) (2)
<style id=“s1” >
</style>
var s1 = document.getElementById (“s1”) ;
var sheet = s1.styleSheet ;
var ruleset = sheet.cssRules ;
// 룰셋에 새로운 빈 룰을 0 번째 룰로 추가한다
sheet.insertRule (‘p{}’,0) ;
// 0 번 룰을 가져온다
var rule = ruleset[0] ;
// 룰의 스타일 객체에 직접쓴다
rule.style[“margin”] = “10px 0” ;
cssStyleDeclration
객체
DOM Element
style
styleSheet
객체
style TAG
cssRules[ ]
객체
7
HTML5
 Webkit Rendering
* Web Engine : Webkit (Safari, Chrome), Gecko (Moziila-FireFox), Tridant (IE), Opera
* Render tree 기준은 Frame 이다
 Rendering is effected by CSS property
* Parent element 가 display:none 으로 되면 하위 element 도 display:none 이 된다
* The GC (garbage collection) conditions are : Removed in DOM and Render Tree AND free reference
CSS Property DOM Tree Render Tree Transparency Value
display:none O X - display: none/inline/block
visibility:hidden O O 0% visibility: hidden/visibility/inherit/collapse
HTML
PARSER
CSS
PARSER
DOM
Tree
Attachment
HTML
Style
Sheet
Style
Rules
RENDER
Tree
Layout
GFX
Context
8
HTML5
 HTML5 에서 신규로 지원되는 Reference Object 들에 대한 개략적인 소개이다
1. document.getelementByClassName
. 기존의 ID, Name 에서 확장하여 Class 명으로 해당되는 Elements List 를 구하며, Object 을 Reference 하기 위함이다
. ID 와 Name 은 element 들이 고유하게 가져야 하는 정보이나 class 는 여러 element 를 지칭 할 수 있다
2. Web Storage : Client side (Browser) data base 기능을 의미한다.
3. Web SQL Data Base : Browser 내장 data base 에 SQL 을 통해 질의하는 API 이다
4. Web App Cache API
5. Web Worker
. 웹 어플리케이션이 주 문서와 병렬적으로 Script 를 백그라운드로 수행할 수 있게 한다
. Thread 기반 메시지 처리 이다.
6. Web Socket
. 서버와 IP 통신을 하기 위한 Client 용 TCP socket 개념의 API 이다 (socket, send, recv)
7. Navigator.getlocation
9
HTML5
 Window (tab 단위로 불린다)
- 하나의 Window 는 하나의 frame 과 하나의 document 를 지닌다
- iframe (inline frame) 태그는 Child window 가 생성되며, 두 window 가 하나의 frame 을 사용하는 개념이다
(render tree 는 Frame 기준이다)
- Link 태그는 동일한 하나의 Window 내에서 새로운 document 로 대체(replace) 되는 것이다
(Attribute 을 통하여 새로운 Window 와 새로운 Frame 을 사용하는 Link 도 가능하다)
- 동일한 Window 내에서 Linked 되어진 document 들 간에 forward, previous 기능이 가능하다
Window-Main
(daum.net)
Document-Main
Frame A
Frame 이란 보여지는 틀 이다
Window-Main
(naver.net)
Document-Main
Frame A
Window-Child
(naver2.net)
Document-Sub
Window-Main
(daum.net)
Document-Main
Frame A
Document-A
Document-B
Link
Link
W3school.com 에서 Practice 도 상기 iframe 을 이용한다
. 좌측 (Practice) : sub document 를 작성한다
. 우측 (결과) : iframe 의 위치
10
HTML5
 HTML5 에서 TAG 종류이다
종류 Description
선언 과 구조
Sectioning
Heading / Footer
Content Grouping
Link
Phrase elements
Style
Formatting
Change Tracking
List
Table
Form
Embedded content
Metadata
Interactive content
Scripting
<html> <head> <body>
<block_quote> <body> <details> <fieldsec> <td> <figure> <article> <nav> <aside> <section>
<header> <h1~h6> <hgroup> <footer>
<block> <quote> <div> <hr/> <br/> <span> <wbr/> <pre> <figure>
<a> <area> <link>
<abbr> <cite> <code> <dfn> <em> <figcaption> <u> <var> <kbd> <mark> <g> <s> <samp> <strong> <sub> <sup> <time>
<b> <i> <pre> <small> <u> <style>
<bdo> <bdi > <rp> <rt> <ruby>
<ins> <del>
<ol> <ul> <li> <de> <dt> <dd>
<table> <caption> <colgroup> <col> <thead> <tr> <tu> <tfoot> <tbody> <td>
<form> <button> <fieldset> <input> keygen> <label> <meter> <datalist>
<audio> <video> <canvas> <embed> <source> <track> <figure> <figcaption> <iframe> <img> <mathml> <object> <paran> <svg>
<base/> <command/> <link/> <meta/> <style> <title>
<a> <button> <command> <details> <keygen> <label> <map> <menu> <select> <sumary>
<script> <noscript>
Deprecated in
HTML5
<frame> <font> <div> <big> <acromym> <applet> <strike> <tt>
Private marquee (IE)
11
HTML5
 HTML 5에서 규정된 Event Type 종류이다 (편의상 Media 및 CSS3 Animation 관련 event 는 제외한다)
종류 Event Type New Description
Mouse onclick
ondbclick
ondrag
ondragend
ondragenter
ondragleave
ondragover
ondragstart
ondrop
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onscroll
-
-
New
New
New
New
New
New
New
-
-
-
-
-
New
New
Fires on a mouse click on the element
Fires on a mouse double-click on the element
Script to be run when an element is dragged
Script to be run at the end of a drag operation
Script to be run when an element has been dragged to a valid drop target
Script to be run when an element leaves a valid drop target
Script to be run when an element is being dragged over a valid drop target
Script to be run at the start of a drag operation
Script to be run when dragged element is being dropped
Fires when a mouse button is pressed down on an element
Fires when the mouse pointer moves over an element
Fires when the mouse pointer moves out of an element
Fires when the mouse pointer moves over an element
Fires when a mouse button is released over an element
Script to be run when the mouse wheel is being rotated
Script to be run when an element's scrollbar is being scrolled
Key Board onkeydown
onkeypress
onkeyup
-
-
-
Fires when a user is pressing a key
Fires when a user presses a key
Fires when a user releases a key
Form onblur
onchange
oncontextmenu
onfocus
onformchange
onforminput
oninput
oninvalid
onslect
onsubmit
-
-
New
-
New
New
New
New
-
-
Fires the moment that the element loses focus
Fires the moment when the value of the element is changed
Script to be run when a context menu is triggered
Fires the moment when the element gets focus
Script to be run when
Script to be run when a form gets user input a form changes
Script to be run when an element gets user input
Script to be run when an element is invalid
Fires after some text has been selected in an element
Fires when a form is submitted
Window onload
onunload
onstorage
onpopstate
-
-
New
New
Fires after the page is finished loading
Fires once a page has unloaded (or the browser window has been closed)
Script to be run when a Web Storage area is updated
Script to be run when the window's history changes
12
HTML5
 구조적 표현을 처리하는 CSS 에 대한 개략적인 개념이다
. 선택자 (Selector) 란 어느 element 를 지칭하는가를 지정하는 script 이며, 개별 혹은 복수개의 element 가 선택된다
. JS 에서도 동적으로 CSS properties 를 변경시킬 수 있다 : getElementById().style.propertie
Java
Script
Properties selector
< Basic Properties>
. Background
. Color
. Text , Overflow
. Font
. Positioning
. Display / visibility
. Box /Margin/Boarder/Padding
. List style
. Table
. Column
. Grid
. Linebox
< CSS3 Properties>
. 2D/3D transform
. Transition
. Animation
< Advanced Properties>
. Hyperlink
. Generated Content
. Marquee (Text 흐름)
. Content for paged media
. Paged Media
. Print
. Ruby
. Speech
. User Interface
. @media
. @font-face
. @keyframes
Elements
< Selector 적용방법>
1) 선택자 : *(전체) / element (특정 element 전체) / # (특정ID) / . (특정 class)
2) 선택자 조합
div,p ; Selects all <div> elements and all <p> elements
div p ; Selects all <p> elements inside <div> elements
div>p ; Selects all <p> elements where the parent is a <div> element
div+p ; Selects all <p> elements that are placed immediately after <div> elements
3) 의사: 특정 element 에 대한 상태 및 node 순서에 따른 선택 (element:상태)
a: link/visited/active/hover
input: focused/enabled/disabled/checked
p: first-letter/first-line/before/after/lang
p: first-of-type/last-of-type/only-of-type/nth-of-type/nth-last-of-type
p: first-child/only-child/nth-child/nth-last-child/last-child
4) 특정 element 가 지니는 attribute [attribute] 의 속성값을 지닌것.
[attribute]
[attribute = value ] ; = / ~= / |=
element[attribute ^=value] ; ^= / $= /*=
<style> ~ </style>
13
HTML5
 CSS Box Model
. HTML 의 모든 element 는 Box 형태로 간주된다 (Render 적 관점)
. DIV 을 예로 들어 기본적인 CSS Property 를 지정하면 아래와 같다
div {
position: fixed ;
width: 300px;
height : 300px ;
left : 20px ;
top : 20px ;
padding: 25px;
border: 25px solid navy;
margin: 25px;
background-color: #00ff00;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
display: block ;
}
14
HTML5
 CSS3 Animation Property
Java Script 를 이용하지 않고, CSS3 속성으로 Render 객체 대상을 동적으로 변화 시키고자 함 이며, 주로 GPU 를 사용한다
1) Transform (-webkit-transform: rotate)
. 회전(Rotate), 비틈(Skew), 확대/축소(Scale), 이동(Translate)
. 2D는 회전 시 시계방향 또는 반 시계 방향으로 회전을 시킨다면, 3D는 좌우, 위아래, 앞뒤로 움직임을 줄 수 있다.
2) Transition (-webkit-transition: )
. 객체가 지닌 CSS Property (하나 혹은 다수)을 변경할 때, 속성이 변경되는 속도 를 조절하는 목적이다
. webkit-transform 도 지정 가능한 Property 에 해당된다
. Property, Delay, Duration, Timing-function 4가지 세부속성을 지닌다
3) Animation : -webkit-animation : myAnimation 5s linear infinite
@-webkit-keyframes myAnimation { // keyframe
0% {background: red; left:0px; top:0px;} // background 대신에 webkit-transform 을 줄 수 있다
25% {background: yellow; left:200px; top:0px;}
50% {background: blue; left:200px; top:200px;}
75% {background: green; left:0px; top:200px;}
100% {background: red; left:0px; top:0px;} }
#myID { // 세부 property 지정
-webkit-animation-name:myAnimation; /* 키프레임의 이름을 지정합니다 */
-webkit-animation-duration:2s /* 애니메이션의 총 길이를 시간으로 지정합니다. 2s는 2second(=2초) 입니다. */
-webkit-animation-timing-function:ease /* 타이밍 펑션을 지정합니다. ease는 처음과 끝을 부드럽게 합니다 */
-webkit-animation-iteration-count:infinite/*반복횟수를 지정합니다. infinite는 무한반복입니다. */
-webkit-animation-direction:normal /*방향을 지정합니다. normal은 정방향으로 진행합니다 , reverse, alternate, alternate-reverse */
-webkit-animation-play-state:running /*애니메이션의 진행 상태 입니다. running, paused*/
-webkit-animation-delay:0s /*애니메이션의 시작전 지연시간을 지정합니다. */
}
<animation-timing-function의 값>
ease -> 시작과 종료를 부드럽게 합니다. linear -> 모든 애니메이션이 일정한 간격으로 작동합니다.
ease-in -> 서서히 시작합니다. ease-out -> 서서히 종료됩니다. ease-in-out -> 서서히 시작하여 서서히 종료됩니다.
cubic-bezier(x1,y1,x2,y2) -> 3차원 배지어(bezier) 곡선의 값을 직접 입력하여 진행합니다.
15
HTML5
 CSS3 Animation 개념
. 해당 Animation 의 Thread 가 생성되어 시나리오 에 맞추어 CSS property 를 변경할 것 으로 추정
Element
Object
Scenario Option
@Keyframes{ // 시나리오 틀 이다
step(x %) {actions}
step(x %) {actions}
step(x %) {actions}
step(x %) {actions}
}
* Actions 는 CSS property 를 의미한다
(예: position, color, transform ,,,)
* from == step 0 %
to == step 100 %
. 시나리오 단위시간
. 동작모드
. Loop Count
. 방향
Animation
Thread
16
HTML5
 Sample of CSS3 Animation
CSS 에 있는 Marquee Property 를 사용치 않고,
GPU 를 사용하기 위하여 Animation 과 Transform 을 이용하여 Text 흐름을 구현한 예 이다
this.setMarquee = function( option )
{ // option.target : 마퀴 적용 할 태그 // option.title : 마퀴 적용할 태그 안에 제목 문자열이 들어있는 태그 ( <a> tag ?)
// option.fontSize : 마퀴 대상의 width와 제목 문자열의 width를 비교해서 제목 문자열의 width가 더 길 때만 마퀴를 적용하는데 이 때 비교에 사용할 제목 문자열의 폰트 크기
// option.fontWeight : 폰트 두께 지정 // option.animationRuleName : 애니메이션 룰에 사용할 이름.
// option.condition : 기본적으로 canvas 태그를 이용해 text의 넓이를 구한 후 부모 객체의 넓이와 비교하여 넓이를 구하지만, dm condition 항목을 통해 추가 조건을 넣을 수 있음.
var self = this;
if( !option.fontSize ) option.fontSize = 20; if( typeof option.fontSize === 'number' ) option.fontSize += 'px';
if( !option.fontWeight ) option.fontWeight = ''; if( !option.animationRuleName ) option.animationRuleName = 'home-menu-marquee';
clearTimeout( this.marqueeTimeoutId );
this.marqueeTimeoutId = setTimeout( function()
{ var width = option.target.width(),
text = option.title.text().trim(),
txtWidth = self.getTextWidth( option.title.text().trim(), option.fontSize + ' ' + option.fontWeight + ' YoonGothic770' ); // using Canvas measureText method
if( parseInt( width ) - 10 <= parseInt( txtWidth ) || option.condition )
{ var rule = option.animationRuleName + " {"
+ "0% { -webkit-transform:translateX(0px); opacity:1}"
+ "49% { -webkit-transform:translateX(" + ( parseInt( txtWidth +50 ) * -1 ) + "px);opacity:1}"
+ "49.0001% { -webkit-transform:translateX(" + ( parseInt( txtWidth + 50 ) * -1 ) + "px);opacity:0}"
+ "49.0002% { -webkit-transform:translateX(" + parseInt( txtWidth + 50 ) + "px);opacity:0}"
+ "49.0003% { -webkit-transform:translateX(" + parseInt( txtWidth + 50 ) + "px);opacity:1}"
+ "100%{ -webkit-transform:translateX(0px); opacity:1} }";
if( self.style.cssRules.length != 0 ) self.style.deleteRule( 0 );
self.style.insertRule( "@-webkit-keyframes " + rule, 0 );
option.title.addClass( 'start' );
option.title.css(
{ text-overflow' : 'clip',
‘ overflow' : 'visible',
'-webkit-animation' : option.animationRuleName + ' ' + ( text.length * 500 ) +'ms linear infinite',
'width' : ( txtWidth + 100000 ) + 'px',
'text-align' : 'left'
} );
}
else
{ option.title.removeClass( 'start' );
option.title.css(
{ 'text-overflow' : 'ellipsis',
'overflow' : 'hidden',
'-webkit-animation' : ''
} );
17
HTML5
 Interaction with Server
. 서버에 data 를 요청하거나, 보내거나 혹은 특정한 작업 (ASP,PHP) 을 요청하는 client 의 동작은 4가지로 분류 할 수 있다
. Performed by LOADER in Webkit
* URL 은 Local File system 접근도 가능하다
* 한번 Retrieve 한 Data (document, file, image ) 는, Webkit 내부에 cached 되어지며 (특정한 버퍼의 용량이 부족하면 Update),
Cache 를 사용하지 않고 새로이 retrieve 하기 위하여는 다음 장 의 Bypassing the cache 를 참고한다,
< Java Script>
window.webSocket()
TCP/IP 서버
(Web Socket Server)
send() / recv()
< Java Script>
window.XMLHttpRequest()
TCP/IP 서버
(Web Server)
http get/post
< Element in HTML>
<form> action=“”
TCP/IP 서버
(ASP/PHP Server)
http post/get
< Element in HTML>
<a> href=“url”
<xxx> src = “url”
TCP/IP 서버
(Web Server)
http get
18
HTML5
 Bypassing the cache
A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate.
For example:
http://foo.com/bar.html  http://foo.com/bar.html?12345
http://foo.com/bar.html?foobar=baz  http://foo.com/bar.html?foobar=baz&12345
Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.
You can automatically adjust URLs using the following code:
var oReq = new XMLHttpRequest();
oReq.open("GET", url + ((/?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
oReq.send(null);
19
HTML5
 XHR (XMLHttpRequest) Object for AJAX
< Java Script>
window.XMLHttprequest()
TCP/IP 서버
(Web Server)
http get
< Method > xhr = new XMLHttpRequest
open ( METHOD, url, async) // GET,POST,HEAD
send () // Null , XMLFile, Form , Text
setRequestHeader(header,value) //
overrideMimeType("text/plain; charset=x-user-defined"); // Handling binary data
addEventListener ("progress", updateProgress, false); // progress,load,error,abort
abort()
< Event Callback >
onload()
onreadystatechange()
ontimeout()
< Attribute >
readyState // 0,1,2,3,4 // 0 Uninitialized, 1 Loading, 2 Loaded, 3 Interactive, 4 Completed
status // 200,403,404,500 for http status code from the server
responseXML // xmldoc = hr.responseXML
responseText // textstring = hr.responseText , normally UTF-8
timeout
< XHR2 New Feature since 2012>
< Attribute >
responseType // “arraybuffer” “blob” “file” “formdata”
response // arraybuffer = hr.response // with the responseType
Xml,Text,Arraybuffer,,
20
HTML5
 Link (a) Tag , connected to
1) another document, specified with URL, the window shall be same or new by attribute “target”
2) email
3) Java Script
4) Move View focus to specific element
 Canvas TAG
. Canvas 는 Graphics 를 위한 Container 이다 (Canvas == Container for graphics)
. getContext(“2d” or “webgl” ) 를 통하여 얻어진 Canvas 객체에 Texture 를 그리는 작업이다 (webgl 은 3d 에 해당)
. Texture 는 일반적인 Rectangle, Text, Path (line, polygon, circle) 과 Image 를 대상으로 하며, Transform 행위도 가능하다
Texture
Fill Style
. Color
. Gradient
. Pattern
Stroke Style
. Color
. Gradient
. Pattern
< Rect create then draw>
(방법1) createRect  fill or stroke
(방법2) fillRect
(방법3) strokeRect
< Text create then draw>
(방법1) fillText
(방법2) strokeText
< Path create then draw>
. beginPath
. stroke
21
HTML5
 Plug-In
. Plug-In 은 HTML5 에서 제공하는 표준적인 객체가 아닌 시스템 (Webkit) 의 Native 기능 과 연결되는 기능이다
. object 혹은 embed Tag 를 사용하여 시스템이 제공하는 Plug-in 사용을 명시한다
. 참고로 Web page 내의 Youtube 동영상 play 는 object 에서 iframe 으로 변경 되었다
html ActiveX
NPAPI
PPAPI
Native
Object
object / embed
ActiveX : MS IE 에서 사용
NPAPI : Webkit 계열에서 사용,
(netscape plug-in API)
Flash Player
Applet
기타 (Security)
22
Java VS Java Script
 Java 는 Programming Language 이며, JS 는 ECMA-262 를 기초로 하는 Script Language 이다
 Java 는 Type check 가 엄격하며, 정적인 Class 를 기반으로 객체지향 (Instance 객체생성 과 상속) 한다
Instance 객체생성과 상속이 명확하게 구분되어 있다 (new 와 extend).
 JS 는 Type check 가 느슨하며, 동적인 (객체의 변형이 가능함) 함수객체 (생성자 함수)를 기반으로 객체지향 한다
Instance 객체생성 과 상속이 명확하게 구분되어 있지 않고, 다양한 패턴을 활용한다  이래서 쉬운듯 어려운 것이 JS 이다
구분 객체생성 (new) 객체상속(extend)
멤버변수 Instance
(독립된 멤버변수)
공유 및 확대
멤버
메소드
공유 공유, 확대 및 Overriding
Class-A
Class-B Class-C
Class-D
extend
new
new
JAVA
. 기본적으로 Constructor 는 Instance 화 되고
Prototype 은 공유 및 Overriding 한다
. 패턴에 따라 Constructor 만 Instance 시키고
Prototype 은 사용하지 않거나, 그 반대의
상속을 적용한다.
함수객체
Constructor Prototype
새로운 객체
new
Java Script
23
Java VS Java Script
 Instance 객체생성 과 상속을 Java 와 JS 간 비교하면 아래와 같이 정리할 수 있다
JAVA Java Script
객체생성 (new) 객체상속 (extend)
멤버 변수 Instance
(독립된 멤버변수)
공유 및 확대 Instance
멤버 메소드 공유 공유, 확대 및 Overriding Instance
Prototype 객체
(변수 와 메소드)
- 공유
24
Java VS Java Script
 소스 code 에서 부터 CPU 에 Instruction 되는 과정을 비교한다
Source
(a.java)
Compiler
(javac)
Byte Code
(a.class)
ByteCode
Verifier
Memory
Class
Loader
Inter
preter
CPU
Java
JVM
Source
(a.js)
JS Engine
(Interpreter)
MEMORY
CPU
Java Script
25
변수 (Variable)
 특징
. 변수 란 특정한 data 를 지닌 공간을 의미하며, 이름을 지닌다 (var reference-name = value)
. JS 는 Type check 가 약한 특징으로, data type 에 대하여 사전에 type 을 명기하지 않고 Assignment 과정에서 (a=x) 결정되며,
동적으로 변경이 가능한 특징을 지닌다 (Number 에서 Function 으로도 변경이 가능하다)
. Primtive data type 이든 모든것은 객체 적 성격을 지닌다 : String, Date, Array [], Object {}, Function 들은 객체이다.
* 실제 typeof 로 확인하여 보면 “object” 으로 보인다  jQuery.type() 을 사용하면 세부 type 알 수 있다
// Variable Types
var a = 10 ; // number
var b = 3.314 ; // number
var c = true ; // boolean
var d = "korea" ; // string
var e = new Date() ; // object (* not date)
var f = [] ; // object (* not array)
var g = {} ; // object
var h = /pattern/i // object (* not RegExp)
var i = function(){} ; // function
a = function(){} ;
document.write(typeof a + "<br>"); // function
// Variable Types
var k =192;
var y ;
document.write(typeof y + "<br>"); // number
y = k.toString() ;
document.write(typeof y + "<br>"); // string
var f = [“samsung”,”hyundai”} ;
var x = f ; // x have a same value from f
26
변수 (Variable)
 특징
. 변수가 생성되면 내장객체 (Browser가 제공하는) 의 prototype 을 자동으로 상속하여 공유한다
이것을 기반으로 prototype 이 제공하는 범용용도의 API 를 사용할 수 있다.
ARRAY
< Properties>
: constructor, length
< Prototype Methods>
: concat, indexOf, join, lastIndexOf
: pop, push , reverse, shift, slice, sort,
: slice, toString, unshift, valueOf
OBJECT
< Properties>
: constructor
< Prptotype Methods>
: hasOwnProperty
: isPrototypeOf, propertIsEnumerable
: toLocaleString
: toString, valueOf
FUNCTION
< Properties>
: constructor, prototype
<Prototype Methods>
: apply, call, bind
: toString, valueOf
STRING
< Properties>
: constructor, length, prototype
< Prototype Methods>
: charAt, charCodeAt , fromCharCode
: concat, indexOf, lastIndexOf
: localeCompare
: match, replace, search, slice, split
: substr, substring
: toLowerCase, toUpperCase, toString
: trim, valueOf
Array.
prototype
Array
Object.
prototype
Object
Function.
prototype
Function
String.
prototype
String
Arguments.
prototype
Function
호출시
Arguments
< Properties>
: caller
: callee
: length
27
변수 (Variable)
 특징
. 내장객체 사용방법
<String Method 사용 예>
url += a.toString ;
url = url.concat(“/temp/”) ;
charCodeAt(); // return unicode from string
<arguments 사용 예>
var args = Array.slice(arguments);
28
변수 (Variable)
 특징
. 접근영역 에 따라 전역변수 (Global Variable) 와 함수내의 Local Variable 로 분류할 수 있다
. 전역변수 는 메모리에 항상 상주하며, 어디서나 접근이 가능하다
. Local Variable 는 해당함수가 호출될때 메모리에 존재하고 종료되면 소멸되며, 해당 함수 내 에서만 접근이 가능하다
일반객체
. Property
함수객체
. Property
함수객체
. Property
Window
. Property
전역 Variable Local Variable
일반객체
. Property
29
변수 (Variable)
 특징
. 일반객체들은 내부의 일반객체들을 포함하여 전역변수에 속한다 (예 참조. myObj1 – myObj2 )
. 함수객체내의 변수들은 기본적으로 local variable 이나, 선언방법에 따라 Static 으로 사용이 가능하다
- Local variable : 함수가 return 되면 메모리에서 소멸된다
- Static variable : Global 한 접근은 안되나, 함수가 return 되더라도 메모리에 남아있다
. 함수객체의 property 이나 함수 바깥에서 선언된것들은 전역영역 이다.
var myObj1 = {
abc : 10,
myObj2 : {},
method1 : function()
{
document.write("First" + "<br>");
}
} ;
myObj1.myObj2.method2 = function()
{
document.write("Second" + "<br>");
myObj1.method1() ;
}
myObj1.myObj2.method2() ;
< Result >
Second
First
var h = function(init){ // Function (FE)
var kka = 100 ; // Local
if(init==true)
kkb = 1 ; // Static (without var)
else
kkb++ ;
document.write(kkb + "<br>"); //1,2,3,,,
};
h.kkc = 300 ; // Global
document.write(h.kka + "<br>"); // Undefined as Local
document.write(h.kkb + "<br>"); // Undefined as Static
h(true) ; // 1
h() ; // 2
h() ; // 3
30
변수 (Variable)
 Object
. Plain Object 이란 쌍 (key/value) 을 지닌 data 의 set 이다
. Object (일반객체 혹은 함수객체) 의 구성요소인 property 와 method 에 대한 추가 시 부여 방법은 아래와 같이 세 가지 방법이다
1) obj1.name = ;
2) obj1[0] = ;
3) obj1[“name”] = ; // obj1.name 과 동일하다  jQuery 에서 함수객체에 함수를 추가하는 방법으로 사용된다
* 함수도 Property 추가 시 상기 부여 방법이 동일하게 사용된다 (동적특성)
* [0] 방법은 Closure - Memoization 패턴에서 많이 사용된다
var obj1={
a1:1
};
// Property 추가
obj1.a2=2 ;
obj1.a3=function(){document.write("a3")} ;
obj1[0]=function(){document.write("a0")} ;
obj1["kk"]=function(){document.write("kk")} ;
document.write(typeof obj1["a2"],obj1.a2) ; // number,2
obj1.a3() ; // a3
obj1[0]() ; // a0
obj1.kk() ; // kk
obj1=obj1||{} ; // 기존에 있으면 유지하고, 없으면 객체 {} type 지정을 의미한다
31
변수 (Variable)
 Array :
. 내부요소에 대한 값만 지니며 이름 은 지닐 수 없고, 이름대신 [index] 를 사용 할 수 있다
var a=["kkk",1,"zzz"] ; // a[0] a[1] a[2]
document.write(a.length + "<br>"); // 3
a[3] = "yyy" ; // 추가함
document.write(a.length + "<br>"); // 4
a.kka = 10 ; // 인정안됨
document.write(a.length + "<br>"); // 4
32
객체
 객체 의 정의
. 포괄적 : 이름 과 값을 지닌 data (Property) 의 집합 및 data 를 조작하기 위한 Method 가 하나로 묶인 것
. Java Script 에서 객체란 : Property 의 집합 과 하나의 prototype object 을 지니고 있다
. Method : 특정함수가 저장된 객체의 Property 로 정의하며, 객체의 속성을 취득 및 변경 하기 위한 창구이다
객체의 프로퍼티에 할당되어 객체를 통해서 호출되는 함수를 메서드라 부른다.
. 객체의 개념 모습
 객체 는 재사용 을 위하여 객체생성 (Instance) 과 객체상속 이라는 Behavior 를 지닌다
. JS 에서 객체생성시 모든 객체는 내장객체 인 Object 객체에 상속된다
. 상속은 Property 에 대한 공유 와 확대를 위함이다
객체
(Object)
Properties
Methods Function(){}
사용자
33
객체
 객체 의 생성 방법 : 세가지 로 분류된다
1) Literal 적 방법 :
. var myObj1 = {} ; // 가장 일반적인 객체의 생성방법 (원시객체)
2) 생성자 를 이용 (new) :
. var myObj2 = new Object() ; // 내장객체 를 이용, 권장하지 않는다
. var myObj3 = new FunctionObjA ; // 생성자 함수객체 (constructor function) 를 이용  가장 일반적인 Instance 생성 과 상속 방법
3) var myObj4 = Object.create(myObj1 )
. ECMA5 부터 지원되는 기능이며, IE Browser 에서는 아직 지원이 되지 않는다
. myObj4 는 함수객체이며, 일반객체를 함수객체가 상속하는 개념이다
*주1. var kkk = new myObj1 ; // 이런 경우 같이 기존의 객체를 이용하여 new 는 불가능 하다 (할 이유도 없을 것이다)
*주2. var kkk = myObj1 ; // 이 경우에는 “kkk” 라는 object 이 생기는 것이 아니고 다만 “myObj1 ” 를 reference 할 뿐이라,
“kkk” 는 “myObj1 ” 와 동일한 것이다.
34
객체
 객체 에 구성되는 Property 는 생성시 사전에 정하거나 혹은 생성후 에 추가 할 수 있다
. 즉, 백지 인 객체만 만들어 놓고 필요할 때 추가할 수 있으며, 삭제 할 수 있다 (이를 동적인 특징이라 한다)
 객체 내부의 Property 중 아래 두 가지는 구성이 불 가능 하며, 객체의 Property 는 전역영역으로 접근이 가능하다
. var 로 시작하는 variable
. 선언함수 (FD) 및 자기호출함수
myObj3 = {
a : 3,
method1 : function() {}
//var abc: 4, // ERROR
// function method2() {} // ERROR
// (function xyz() { }) (); // ERROR
} ;
alert(“myObj1.a) ;
myObj1.method1() ; // Invoke
// 생성시 Property 를 정한다
var myObj1= {
a : 3 ,
b : “school”,
method1 : function () {} // ; 추가하면 안됨
} ;
delete myObj1.b ; // 삭제를 할 수도 있다
// 생성 후에 Property 를 추가한다
var myObj2 = {} ;
myObj2={
a: 1,
method1 : function() {document.write("aa")} // ; 추가하면 안됨
}
// 개별형식으로 만 추가
myObj2.b = 2 ;
myObj2.method2 = function () {document.write("bb")} ;
//myObj2={} ; // 참고-이리하면 비어진 객체가 된다
myObj2=myObj2||{ // {} 방식으로 추가
c:3
}
myObj2.method1() ; // aa
myObj2.method2() ; // bb
// defineProperty 를 이용한 생성 및 속성관리 방법
var myObj3 = {} ;
Object.defineProperty(myObj3, prop1,,,)
35
객체
 defineProperty
. 객체의 특정한 Property 에 대하여 특정한 관리를 할 수 있다
< define 가능한 속성들> -able 들은 boolean 으로서 default false 값을 지닌다
value ;
writeable ; value 를 변경가능여부 , value 를 선언 시 에만 가능
enumerable ; value 의 속성이 enumber 여부
set() ; setter Method, value 가 선언되면 사용 못한다
get() ; getter Method, , value 가 선언되면 사용 못한다
configurable ; set(), get() 과 함께 객체의 정의자체를 변경
하기 예제는 set, get 을 이용하여 하나의 property 에 multi function 을 구성한 예이다.
Object.defineProperty(a={},"prop1",{value:1,writeable:true}) ; // a.prop1=1
Object.defineProperty(b={},0,{value:2,writeable:true}) ; // b[0]=2
document.write(a.prop1, b[0]) ;
a.prop1 = 4 //
b[0] = 5 ;
document.write(a.prop1, b[0]) ; // still 1,2 (?)
Object.defineProperty(c={},"prop1",{
set:function(arg){document.write("set“, arg)},
get:function(){document.write("get")}}) ;
var k=c.prop1 ; // call get()
c.prop1=2 ; // call set(), arg=2
36
객체
 defineProperty
. 하기 예제는 set, get 을 이용하여 하나의 property 에 multi function 을 구성한 예이다.
var curWidget = curWidget || {};
Object.defineProperty(curWidget,'onWidgetEvent',{
set : function(arg0){
this._onWidgetEvent = this._onWidgetEvent || [];
this._onWidgetEvent.push(arg0);
},
get : function(){
return function(eventData){
var _onWidgetEvent = this._onWidgetEvent || [];
for(var i=0,l=_onWidgetEvent.length;i<l;i++){
try {
_onWidgetEvent[i](eventData);
} catch(e) {
}
}
};
}
});
curWidget.onWidgetEvent = function(event){
console.warn("curWidget.onWidgetEvent add 1111 ");
}; // widget event callback
curWidget.onWidgetEvent = function(event){
console.warn("curWidget.onWidgetEvent add 2222 ");
}; // widget event callback
curWidget.onWidgetEvent = function(event){
console.warn("curWidget.onWidgetEvent add 3333 ");
}; // widget event callback
37
객체
 객체생성 시 기본 상속관계
. 객체 가 생성되면 아래와 같이 내장 객체인 Object.prototype 객체를 자동으로 상속(공유) 받는다
. “__proto__” 는 보이지 않는 내부 개념을 의미하는것으로 보인다
 Object 내장객체 는 아래와 같은 세부 property 와 method 를 지닌다
var myObj1={}
properties
methods
__proto__
Object 내장객체
properties
methods
prototype
<Methods>
. create()
. defineProperties()
. defineProperty()
. freeze()
. getOwnPropertyDescriptor()
. getOwnPropertyNames()
. getPrototypeOf()
. is()
. isExtensible()
. isFrozen()
. isSealed()
. keys()
. preventExtensions()
. seal()
. setPrototypeOf()
< Properties>
. prototype
<Prototype Methods>
. prototype.eval()
. prototype.hasOwnProperty()
. prototype.isPrototypeOf()
. prototype. propertyIsEnumerable()
. prototype. toLocalString()
. prototype. toSource()
. prototype. toString()
. prototype. unWatch()
. prototype. valueOf()
. prototype. watch()
< Prototype Properties>
. prototype.__count__
. prototype.__noSuchMethod__
. prototype.__parent__
. prototype.__proto__
. prototype.constructor
var myObj1={} ;
document.write(myObj1.__proto__ + "<br>"); // undefeined
document.write(myObj1.constructor + "<br>"); // function Object() (*** Object.prototype.constructor 의 내용이다)
Object.prototype
constructor
Properties
Methods
38
객체
 객체 트리
. 모든 객체는 하부에 객체를 포함 할 수 있으며, 가장 상위의 객체는 window 내장객체 이다
. 해서, window 를 루트로 하여 객체 tree 가 형성된다
. 함수 호출시 Scope chain 이 형성되며, Execution Context Stack 에서 추가 설명한다
. objC 의 method 를 호출 시 FuncObjA.objC.method() , 즉 루트객체인 window 는 명기하지 않아도 된다
. 이러한 Tree 구조를 이용하여 큰 기능에 대하여 부분 기능별로 모듈화 설계가 가능하며 이를 name space 라 칭한다
전역영역 window
objA FuncObjA
FuncObjC objC FuncObjBobjB
39
함수
 함수 란
. 일반 객체와 유사한 성질을 지닌 객체로서 First Class Object 이며, 실행 context stack 의 유효범위 (Scope) 를 제공한다
. 일반객체와 마찬가지로 자기자신의 property 와 메소드를 지니며, 특정객체를 하부에 포함 할 수 있다
. 생성자함수 는, 일반객체 의 new 대상이 되어 Instance 객체생성 과 상속이 되는 원형객체로 사용된다
. 상기와 같은 사유로, Java Script 는 함수를 기반으로 하는 객체지향 이라 할수 있다
 차례
1) 함수 생성방법
2) 함수의 사용적 특징
3) 용도적 분류
4) 원형객체 로의 사용 (클래스 방식의 상속패턴)
5) CLOSURE 특성
40
함수
 함수 생성방법 : 세 가지로 분류된다
1) 선언함수 (Function Declaration )
. function FunctionName () { } // 함수 invoke 시 FunctionName() ;
2) 표현함수 (Function Expression)
. var referenceA = function () { } ; // 함수 invoke 시 referenceA() ;
. 일반객체 나 함수객체 에 포함되는 내부함수도 이것으로 볼 수 있다 ; myObj1.method : function() {};
. var referenceA = new Function() 도 이것으로 볼 수 있으나, 사용이 권장되지 않는다
. var referenceB = referenceA 는 표현함수를 새로운 변수에 할당하는 것이다
*주1. 함수에 이름이 명기 되었다면 기명함수, 없다면 익명함수 로 불리나 이러한 구분은 실효적이지 못하다
*주2. 선언함수 와 표현함수 의 주요한 차이점 (거의 동일하게 사용된다고 보면 된다)
1) 특정한 상황에서 FD 는 불가능 한 경우 (즉 variable 형 만 가능하다)
. 일반객체 내에서 구성되는 method 는 FD 는 불가능하고 FE 만 가능하다 (객체 설명 페이지 참조)
. 자기호출함수 내의 function 은 FD 는 외부호출 불가능하고 FE 만 가능하다
2) 선언함수는 페이지 로딩이 완료가 되면 Execution Context 의 variable object 에 프로퍼티로 잡히나,
표현함수는 EC 의 VO 에 잡히지 않는다. 이런 사유로 표현함수는 선언이 되고 난 후 호출이 되어야 한다 (HOISTING)
document.write(typeof xyz + "<br>"); // function
function xyz(){
document.write("XYZ-1" + "<br>");
} ;
function xyz(){ // 동일한 이름을 갖는 선언함수가 유효한지 확인유효함
document.write("XYZ-2" + "<br>");
} ;
xyz() ; // XYZ-2, to see replace the function
document.write(typeof xyk + "<br>"); // undefined (HOISTING)
var xyk = function(){} ;
41
함수
 함수 생성방법 : 세 가지로 분류된다
3) 자기호출함수 (Self Invoking) ; 표현함수 류 이면서, 즉시실행함수 라고도 한다
. (function () { } ) () ; // 함수는 누가 호출하는 것이 아니고, 자동으로 invoke 된다
. 일반객체 내에서는 구성이 불가능 하나, 함수객체 내에서는 구성이 가능하다
. 주로 수시로 사용되지 않고 1회성 으로 만 사용되는 초기화가 필요한 부분의 기능을 담당한다
. 특정객체를 argument 로 pass down 시킬 수 있다
. 내부 variable 및 function 은 마치 window 에 속하는 것처럼 전역화 (Global) 되어 진다
(function myFunc1()
{
kka = 100 ; // 전역 (If var then Local)
alert("SI1") ;
function test1(){ // 내부함수
alert("test1") ;
}
test2 = function(){ // 전역 (If var then Local)
alert("test2") ;
}
test1() ;
})() ;
alert(kka) ; // Success
//test1() ; // Error
test2() ; // Success
var f={
abc: 10 ,
};
(function myFunc2($){
alert (f.abc) ;
})(f) ; // Pass down as $
42
함수
 자기호출함수 를 이용하여 new 없이 wrapper 구현
var myObj={} ;
myObj.myFunc = (function () { // 자기호출-1
alert("A") ;
var WACFile = (function() { // 자기호출-2
alert("B") ;
function WACFile(){
this.method1a = function () { alert("m1a") ; } ;
}
WACFile.prototype.method1b = function () {
alert("m1b") ;
return new FileStream ;
};
return WACFile ; // To make CLOSURE
})() ;
function FileStream(){ // 내부함수객체
this.method2 = function () { alert("m2") ; } ;
}
function dfhandle(){ // 내부함수
return new WACFile ;
}
dfhandle1 = function(){ // 전역함수
return dfhandle() ;
}
})() ;
var h1 = dfhandle1() ;
var h2 = h1.method1b() ;
h2.method2() ;
< Wrapper> 구현 패턴정리
1. 표준적인 함수객체를 사용 : new
2. 일반객체를 싱글톤 으로 사용 : new 없이
3. 자기호출함수 의 전역함수를 이용 : new 없이
43
함수
 함수생성 시 기본 상속관계
. 함수 가 생성되면 아래와 같이 내부객체인 prototype 객체 (일반객체,{}) 가 자동으로 만들어지며, 연관관계는 아래와 같다
 내장객체인 Function 객체는 아래와 같은 세부 property 와 메소드를 지닌다
function f(){}
properties
method
__proto__
prototype
Function.prototype
constructor
__proto__
< Properties>
. arguments
. agrity
. caller
. length
. name
. prototype
<Prototype Methods>
. prototype.apply()
. prototype.bind()
. prototype.call()
. prototype. isGenerator()
. prototype. toSource()
. prototype. toString()
< Prototype Properties>
.
function f(){} ;
document.write(f.constructor + "<br>"); // Function()
document.write(f.constructor.prototype + "<br>"); // prototype()
document.write(f.prototype + "<br>"); // Object
document.write(f.prototype.__proto__+ "<br>"); // undefined
document.write(f.prototype.constructor + "<br>"); // f()
document.write(typeof f.constructor + "<br>"); // function
document.write(typeof f.prototype + "<br>"); // object
f.prototype
constructor
__proto__
Function 내장객체
properties
prototype
Object.prototype
44
함수
 JS 함수의 사용적 특징
1) 반환 형이나 매개변수의 개수 와 형이 정의되지 않는다 (Type check 가 느슨하다 라는 특징)
. 매개변수에는 value 혹은 reference (object or function) 가 가능하다
. 반환 (return) 은 없어도 가능하고, 없다면 “undefined” 가 return 되며,
어느 종류의 data type 포함하여 함수 나 객체도 반환형에 사용 될 수 있다 : return function / return { var,function,,}
. 함수가 매개변수로 사용되는 대표적인 예는 callback 함수를 등록하는 것이다 (addEveentListener, setTimeout)
. CLOSURE 라는 특성은 함수가 반환되어 사용되거나, 매개변수로 함수가 사용되는 경우 와 연관되어
지니는 Java Script 에서 중요한 개념이다 (추가 설명)
2) 함수 내에 자손함수 (inner or nested function ) 을 포함 할 수 있다
. 전역공간 의 최소화 및 내부함수를 외부에 노출시키지 않으려는 목적으로 사용된다 (마치 C언어의 static 함수처럼)
. 자손함수 는 return 되어 외부에서 사용이 가능하다
3) 재귀함수 (함수 내에서 자신을 호출 하는 것) 가 가능하다
4) 호출 (Invoke) 되지 않고 실행될 수 있다 : 즉시실행함수
5) 자기 자신을 덮어쓰기를 할 수 있다
function myFunc1()
{
var abc = 100 ;
var abd = "Kwon" ;
var abe = function() {alert("abe")} ; //자손함수
return{ // 객체로 return 하는 예제.
ab: abc,
ac: abd,
ad: abe
}
};
var ret = myFunc1() ;
alert (ret.ab + ret.ac) ;
ret.ad() ;
45
함수
 함수 의 용도적 분류 :
1) 크게 두 가지로 분류 할 수 있다
(1) 생성자함수 : 원형객체로서 사용목적 (2) 일반함수 : 단지 특정 statement 만을 지닌다
*주1. 생성자함수 는 대문자로 시작하며, 일반함수는 소문자로 시작한다
2) 함수 내부구성 Property 는 내부 에서만 사용되며, 바깥에서 동적으로 추가도 가능하다 : Closure –memoization 에서 활용
function myFunction1 (a){
this.a = a,
this.method1 = function () {} ;
}
myFunction1.prototype.method3 = function () {} ;
document.write(typeof myFunction1 + "<br>"); // function
var myObj1 = new myFunction1 ;
myObj1.method3() ;
function kkb (a,b){ // 선언식함수 (FD)
return a*b ;
}
var kkc = function (a,b){ // 표현식함수 (FE)
return a*b ;
}
Kkb(1,2) ;
document.write(typeof kkb + "<br>"); // function
function myFunc() {
var a=10 ; // local
b=20 ; // local
c=function(){document.write(+a,+b)} ; // 내부함수
c() ;
}
myFunc.d = 30 ; // 추가
myFunc.e = function(){document.write(“aa”)} ; // 추가
myFunc[0]=function() ; // 추가
myFunc[“f”]=function() ; // 추가 == myFunc.f=function(){}
myFunc() ;
document.write(myFunc.b) ; // undefined
document.write(myFunc.d) ; // 30
myFunc.e() ; // aa
myFunc[0]() ;
myFunc.kk() ;
46
함수
 함수 의 용도적 분류
3) 생성자함수 는 단독으로 사용을 하지 않으며, Instance 객체를 위한 원형객체 이다
생성자함수 를 세부적으로 구성하는 구성요소는 아래와 같으며, prototype 은 하부 객체임을 알수있다
function myFunction1 (a){
this.a = a ; // Instance 대상변수 (멤버 변수)  Constructor
var kka = 10 ; // 내부변수
this.method1 = function () {} ; // Instance 대상 method (멤버 메소드)  Constructor
method2 = function () {} ; // 내부 메서드, 표현식
function kka() {} // 내부 메서드, 선언식
}
myFunction1.staticMethod = function() ; // STATIC 메서드 추가
// prototype 정의
myFunction1.prototype.value = true ;
myFunction1.prototype.SUCCESS= 1 ; // Constant
myFunction1.prototype.method3= function () {} ; // 상속(공유) 을 위한 prototype
document.write(typeof myFunction1.prototype + "<br>"); // object
myFunction1.staticMethod() ; // Can access here
//myFunction1.method1() ; // ERROR – Instance 객체 에서만 생성되는 method
//myFunction1.method2() ; // ERROR – 내부함수 접근불가
//myFunction1.method3() ; // ERROR – Instance 객체 에서만 공유되는 method
47
함수
 함수의 용도적 분류
4) prototype 확대
(1) prototype 은 일반객체 로서 객체의 성격 과 동일하게 객체 구성 분 (property) 을 동적으로 추가 할 수 있다
(2) 동적으로 추가되는 것도 Instance 생성객체에서 사용가능 하다
function K(){ // 함수객체
}
K.prototype ={ // prototype 객체 property 사전구성
a:3,
b:function(){document.write("aa")}
}
var a = new K() ;
// protype 객체 property 추가
K.prototype.e=function(){document.write("cc")} ;
K.prototype.f=20 ;
a.b() ;
a.e() ;
48
객체 와 함수
 일반객체 와 함수객체 의 차이점 정리
. 둘 다 객체적 성격을 지녀서 내부에 property, 일반객체 및 함수객체를 포함 한 다.
. typeof 로 확인시 “object” 와 “function” 으로 구분이 된다
. 일반객체는 원형객체로서 사용은 되지 못하고, 싱글톤 객체로만 사용된다
. 함수객체는 원형객체로 사용되며, 객체의 생성부분을 위한 constructor 와 상속을 위한 prototype 을 지닌다.
이를 위하여 prototype 이라는 property 명으로 내부객체 (일반객체) 를 지닌다.
49
함수 – 객체화 및 상속
 생성자함수 를 원형객체로 하여 아래와 같은 기본적인 객체화 및 상속을 적용한다
. 객체화 로 생성되는 myObj1 이 type 이 함수가 아니고 일반객체 (object) 임을 기억해라.
. “instanceof” 라는 key word 를 사용하여 원형객체 임을 알 수 있다
var myObj1 = {} ;
document.write(myObj1.constructor + "<br>"); // function Object()
var myObj1 = new myFunction1 ;
document.write(typeof myObj1 + "<br>"); // object
if(myObj1 instanceof myFunction1)
document.write("Inherited"+ "<br>"); // Inherited
myObj1.method1() ; // Instance method
myObj1.method3() ; // 상속(공유)
document.write(myObj1.__proto__ + "<br>"); // undefined
document.write(myObj1.constructor + "<br>"); // function myFunction1()
Object.
prototype
myObj1
myFunction1.
prototype
myObj1
50
함수 – 객체화 및 상속
 생성자함수 의 원형객체 사용
생성자함수 를 원형으로 하여 새로운 Instance 객체 생성을 하거나, 상속 (공유) 을 하는것을 클래스방식의 상속패턴이라 하며,
크게는 5가지 방법이 있다
방법1. 기본적인 방법
. constructor (this 로 지니는 property 및 method) 는 Instance 객체에서 new 의 대상이 된다 (복사되어 새로운 것을 지닌다)
. prototype 은 상속의 대상이 된다 (공유를 한다)
constructor
prototype
Instance객체
생성자함수
property
method
공유
Instance
var myObj1 = new myFunction1 ;
myObj1.method1() ;
myObj1.method2() ; // ERROR
myObj1.method3() ;
방법 요약 Constructor 멤버
(this.x ) Instance
Prototype 상속
방법1 기본 O O
방법2 생성자 빌려쓰기-1 O X
방법3 생성자 빌려쓰기-2 O O
방법4 Prototype 공유 X O
방법5 임시 생성자 X O
51
함수 – 객체화 및 상속
 생성자함수 의 원형객체 사용
방법2. 생성자 빌려쓰기 를 이용하는 방법
. 내장객체 (Function.prototype) 의 apply 혹은 call 메소드 를 이용하는 방법 이다
. Constructor (this 로 지니는 Property 및 Method) 는 Instance 객체에서 new 의 대상이 되지만, prototype 은 상속 (공유) 하지 않는다
. 생성자 빌려쓰기 를 이용하여 다중상속 구현이 가능하다
constructor
prototype
Instance객체
생성자함수
property
method
Instance
function myFunction2(name)
{ myFunction1.apply (this,arguments) ;
}
var k = new myFunction2 ("denver") ;
document.write(k.a + "<br>"); // denver
k.method1() ;
//k.method3() ; // ERROR
Function constFunc1()
{ this.kka = 3 ;
this.kkb = function(){} ;
}
Function constFunc2()
{ this.kkc = 4;
this.kkd = function(){} ;
}
function InstanceOnly()
{ constFunc1.apply (this) ;
constFunc2.apply (this) ;
}
var multiInherit = new InstanceOnly() ;
52
함수 – 객체화 및 상속
 생성자함수 의 원형객체 사용
. 기타 상속패턴
방법3. 생성자 빌려주기를 사용 ; Instance 생성과 prototype 을 상속 받는다
방법4. Prototype 을 공유한다 ; Prototype 만 상속한다
방법5. 임시생성자 를 이용한다 ; Prototype 만 상속한다
// 방법3
function myFunction2(name)
{ myFunction1.apply (this,arguments) ;
}
myFunction2.prototype = new myFunction1() ;
var k = new myFunction2 ("denver") ;
document.write(k.a + "<br>"); // denver
k.method1() ; // Okay
k.method3() ; // Okay
// 방법5
function myFunction2(){} ;
function Inherit5(Child, Parent)
{
var F = function() {} ;
F.prototype = Parent.prototype ;
Child.prototype = new F() ;
}
var k = new myFunction2() ;
Inherit5(myFunction2,myFunction1) ;
//k.method1() ; // ERROR
k.method3() ; //상속(공유) --> 되어야 하는데 ERROR 난다 (***)
// 방법4
function myFunction2(){} ;
myFunction2.prototype = myFunction1.prototype ;
var k = new myFunction2() ;
//k.method1() ; // ERROR
k.method3() ; // 상속(공유)
document.write(myFunction1.prototype + "<br>"); // [object Object]
document.write(myFunction2.prototype + "<br>"); // [object Object]
53
함수 - CLOSURE
 CLOSURE 란
. 함수 의 사용적 특징 중에 자손함수를 지닐 수 있고, return 되어 사용될 수 있고, 또한 인자로도 사용가능 한 특징이 있다
. 또한 Execution Context Stack 의 특징에 의하여 EC 는 activated 가 종료되면 내부 변수들은 모두 free 가 되어진다
(별도의 Garbage collector 가 있다 ?)
. 해서, 정리하면 아래와 같은 특징을 CLOSURE 라 한다
1) return 함수에 사용되는 variable 이 free 되어진 상태이나, return 함수에 사용된다
2) return 되는 함수 혹은 매개변수로 사용되는 함수의 scope chain 을 기억하여 해당 variable 을 찾을때 활용하는 것을 지칭한다
3) 이를, Static (lexical) scope 라 칭하며 (in contrast with Dynamic scope), ECMA script 에서는 static scope 방법이 사용된다
 예 (Example)
< Case 1. return function 인 경우 >
var Y = 10 ;
function kka()
{ var Y = 200 ;
return function kkb() {
document.write (Y) ; // 200 not 10
}
}
var retFunc = kka() ;
retFunc() ; // Invoke kkb()
< Case 2. function 이 매개변수인 경우>
var X = 10
function kkc(){
document.write (X) ; // 10 not 100
}
(function kkd(funcArg)
{ var X=100 ;
funcArg() ;
} )(kkc) ; // pass down as “funcArg”
Global
EC
kka
EC
kkb
EC
Global
EC
kkd
EC
kkc
EC
54
함수 - CLOSURE
 CLOSURE 활용 패턴
1) 함수내의 Local Variable 을 마치 static 변수처럼 사용하게 한다
. 즉, closure 가 발생되면, scope chain 에 기억된 함수들의 Variable Object 들은 메모리에서 상주한다
. 이를 이용하여 Local Variable 을 마치 static 변수처럼 사용할 수 있다
. 예제를 통하여, myFunction7() 이 지니는 xyz 이 static 변수처럼 사용 됨을 알 수 있다
// 일반함수 로 사용시
unction myFunction6(k)
{
var xyz ;
if (k==true) xyz = 1 ; // 초기화
else xyz++ ; // lead to NaN
document.write(xyz + "<br>");
}
myFunction6(true) ; // 1
myFunction6(false) ; // NaN
// CLOSURE 로 사용시
function myFunction7()
{
var xyz=1 ;
return function()
{ xyz++ ; // xyz is cached
document.write(xyz + "<br>");
}
}
var retFunc = myFunction7() ;
// document.write(+xyz) ; // can't access
retFunc() ; // 2
retFunc() ; // 3
55
함수 - CLOSURE
 CLOSURE 활용 Pattern
2) 커링 (Curring)
. 원본함수 와 매개변수 일부를 물려받는 새로운 함수를 생성 하는 것을 의미한다
커리할 원래 함수와 인수를 유지하는 클로저를 만드는 방식으로 동작한다.
. 어떤 함수를 호출할 때 대부분의 매개변수가 항상 비슷하다면, 커링 의 적합 한 사용대상이라고 볼 수 있다
. 매개변수 일부를 저장하여 새로움 함수를 동적으로 생생하면 이 함수는 반복되는 매개변수를 내부적으로 저장하여,
매번 인자를 전달하지 않아도 원본 함수가 기대하는 전체목록을 미리 채워놓을 것이다.
. Functional programming 에서 공통적인 사용 모델이다
//1. 기준함수를 설정한다.
function seq( start, end )
{ var i;
for( i = start; i < end; ++i ){
document.writeln( i );
}
}
//2. Closure 함수에서 원함수를 내부함수의 최종 결과를 생성하도록 만든다.
function fixSeqStart( start )
{
return function( end ) {
return seq( start, end ); // start should be closure
} ;
}
//3. 함수를 부분별로 실행한다.
var seq10 = fixSeqStart( 10 );
// Print out numbers from 10 to 20
seq10( 21 );
56
함수 - CLOSURE
 CLOSURE 활용 Pattern
3) 메모이제이션
. 특정한 함수의 결과가 매개변수의 조건에 따라 고정적인 경우, 해당 값을 cached 시켜놓고, 두번째 부터 는 함수를 호출하지 않고
Cached 값을 return 하여 준다 – 성능향상을 위함.
. Cached 를 위하여 원래함수에 Buffer 를 만든다  해당함수의 VO 가 소멸되지않고 cached 되는 원리를 이용한다
. Fibonachi (피보나치) 수열 을 예로 든다 (최초의 두항이 1,2 이고 그 뒤는 앞서는 두항의 합이 그 다음 항의 수가되는 수열)
function memo(f) // //메모이제이션 함수 정의
{
return function (x) { // closure 함수
f.memo = f.memo || {}; // 원래함수 f에 Closure 생성한다
return (x in f.memo) ? f.memo[x] : f.memo[x] = f(x);
};
}
//원래 함수 (피보나치 수열을 구하는 함수)
function fib(x)
{
if(x < 2)
return 1;
else
return fib(x-1) + fib(x-2);
}
// fib.memo={} // static buffer
//함수 실행
var memoFib = memo(fib);
document.write(memoFib(1) + "<br>"); // 1
document.write(memoFib(2) + "<br>"); // 2
document.write(memoFib(3) + "<br>"); // 3 = 1+2
document.write(memoFib(4) + "<br>"); // 5 = 2+3
document.write(memoFib(5) + "<br>"); // 8 = 3+5
document.write(memoFib(6) + "<br>"); // 13 = 5+8
document.write(memoFib(5) + "<br>"); // 8 , CACHED
document.write(memoFib(6) + "<br>"); // 13 , CACHED
CLOSURE
함수
Cached
원래함수
실행
Cached
Buffer
Closure 함수에 인자로 원래 함수 를 준다
Cached
Buffer
Buffer 생성
No
Return from Cached Buffer
Yes
57
Execution Context Stack
 JS 가 Load 되어 실행이 진행중인 (activated, program runtime) code 영역을 ECS 라 한다
. 실행 context : 코드실행의 작은 조각을 capsule 화 한 property 를 가지고 있는 어떤 객체들의 집합
. 특정 Java Script 는 일반적으로 다음과 같은 요소들로 구성될것이며, 전역공간을
 ECMA script 에서 규정한 code (Execution Context) 는 세가지 로 구성된다 : global , function and eval
. global context 는 단 하나로 존재하며, global EC 를 실행하는 객체는 내장객체인 window 이다
. function 과 eval 에 대한 EC 는 다수 개 가 있을 것이다
. 함수가 호출 (Activate) 되어 지면, function ECS 로 진입하고 (Activated), return 되면 해당 ECS 는 소멸되고 caller 의 ECS 로 간다
. 내부함수는 outer function 과는 독립적인 새로운 function ECS 를 지닌다.
. eval 과 setTimeout 은 그 특성 상 function 이 아닌 별도의 ECS 를 지닌다.
// main.js
. variable ; 전역공간
. 일반객체 ; 전역공간
. 선언함수
. 표현함수
. 즉시실행함수
. Expression & Statement
Global
EC
FunctionA
EC
FunctionB
EC
return return
Activate ActivateBegin
58
Execution Context Stack
 Execution Context 세부
. 각 EC 는 Context 의 상태 (state) 를 위한 properties 들을 아래와 같이 지니고 있다.
. VO 는 해당 EC 과 연관된 scope of data 로 정의하며 variables 와 argument 및 선언함수를 store 하고 있다.
*주1. 표현함수 및 자기호출함수 는 VO 에 포함되지 않는다.
이런 이유로 표현함수 에 대한 호출위치는 항상 표현함수 뒤에서 해야하며 이를 HOISTING 이라 한다.
*주2. arguments 는 함수 EC 에서만 존재한다
. thisValue : EC stack 을 실행호출한 어느 context 인 객체 를 의미한다 (EC 에 진입되면 determine 되어지고 변경될 수 없다)
. function EC 가 activated 되어지면, 특별한 object 인 Activation Object (AO) 가 만들 어지며, 이 AO 는 VO 역할을 한다.
Variable Object (VO) [ vars, 선언함수, arguments,, ]
Scope Chain [ VO + All Parent Scope ]
thisValue Context Object
XXXX
EC
function foo(x,y) {
var z = 30 ;
function bar() {} // FD
(function baz() {}); // FE
}
foo (10,20) // invoke (activate)
< Activation Object of foo>
x 10
y 20
arguments {0:10,1:20,..}
z 30
bar <function>
59
Execution Context Stack
 Scope Chain
. 아래와 같은 myFunction1 함수를 Invoke 한다고 하면, 우측 그림과 같은 실행순서, EC 와 Scope chain 이 형성된다
Scope Chain 이란 자신의 함수의 AO 영역에서 발견되지 않는 reference 에 대하여 caller 함수의 AO 영역을 찾는 scope 이다.
var aaa =10 ;
var myObj = {} ;
myObj.myFunction4 = function() // For the Scope Chain
{ var bbb = "BBB" ;
document.write(aaa + "<br>"); // AAA
function kka(){ // FD
var ccc = "CCC" ;
document.write(aaa + "<br>"); // AAA
document.write(bbb + "<br>"); // BBB
//document.write(ddd + "<br>"); // ERROR
}
var kkb = function (){ // FE
var ddd = "DDD" ;
(function kkc(){ // 즉시 실행함수
var eee = "EEE" ;
document.write(bbb + "<br>"); // BBB
document.write(ddd + "<br>"); // DDD
}) () ;
};
(function kkd(){ // 즉시 실행함수
var fff = "FFF" ;
document.write(bbb + "<br>"); // BBB
})() ;
kka() ;
kkb() ;
//document.write(ccc + "<br>"); // ERROR
};
myObj.myFunction4() ;
Global
EC
myFunction4
EC
kkd
EC
kkb
EC
kkc
EC
VO aaa
myObj
kka
EC
AO bbb
kka
AO ddd
AO fff
*주1. kkc 함수의 Scope Chain 은 kkc  kkb  myFunction1  Global 이다.
60
Execution Context Stack
 this 의 정의
. Keyword 로서 특정 객체를 의미한다 (지칭 하거나 객체의 전체 context 를 나타낸다)
(1) 일반객체 내에서는 code 의 소유주 객체를 나타낸다 (예. window.kkb() )
(2) 생성자 함수를 이용하여 만들어진 Instance 객체 의 메소드 (instance or prototype) 내의 this 는 해당객체를 의미한다.
(3) String 이나 Array 같은 내장객체는 객체자체가 context 전체와 동일하게 사용된다
. 생성자 함수 내에서의 this 는 값을 가지지 않고, 신규객체의 Instance 대상 임을 의미한다
< Code 의 소유주 객체를 의미>
document.write(typeof this + "<br>"); // object
var a = "window" ;
document.write(this.a + "<br>"); // window
var myObj1 = {
a:"myObj1",
method1 : function()
{ document.write(this.a + "<br>"); // myObj1
kkb(); // window
}
} ;
var myObj2 = {
a:"myObj2",
method1 : function()
{ document.write(this.a + "<br>"); // myObj2
kkb(); // window
}
} ;
function kkb (){
document.write(this.a + "<br>"); // "window"
}
this.kkc = function(){ // same with window.kkc
document.write(this.a + "<br>"); // "window"
}
myObj1.method1() ; // “myObj1” “window”
myObj2.method1() ; // “myObj2” “window”
this.kkb() ; // "window"
window.kkb() ; // "window"
< 객체의 전체 context 를 의미>
var str1 = "korea" ;
var str2 = "japan" ;
String.prototype.test = function(){
document.write(this + "<br>");
}
str1.test() ; // will print "korea"
str2.test() ; // will print "japan
var ara1 = ["kka","kkb"];
var ara2 = ["kkc","kkd"];
Array.prototype.test = function(){
document.write(this + "<br>");
}
ara1.test() ; // will print "kka,kkb"
ara2.test() ; // will print "kkc,kkd”
var obj1= {a:1,b:2} ;
var obj2= {c:1,d:2} ;
Object.prototype.test = function(){
document.write(this + "<br>");
}
obj1.test() ; // will print "[object Object]"
obj2.test() ; // will print "[object Object]"
var fnc1= function(){a=1} ;
var fnc2= function(){b=1} ;
Function.prototype.test = function(){
document.write(this + "<br>");
}
fnc1.test() ; // will print "function(){a=1}"
<생성자함수의 Instance 객체를 의미)
function myFunction1 (){ // 생성자함수
this.a ;
this.method1 = function () {
document.write(this.a + "<br>");
} ;
}
myFunction1.prototype.method4 = function(){
document.write(this.a + "<br>");
} ;
var myObj1 = new myFunction1 ;
var myObj2 = new myFunction1 ;
myObj1.a = 10 ;
myObj2.a = 20 ;
myObj1.method1() ; // 10
myObj2.method1() ; // 20
myObj1.method4() ; // 10
myObj2.method4() ; // 20
61
Execution Context Stack
 this 의 정의
. Code 의 소유주 객체를 의미한다는 것은 아래와 같이 추가적으로 define 된다
1) window 하부의 일반함수나 global variable 의 this 는 window 이다
2) 일반객체 내부의 this 는 해당객체이다
< Code 의 소유주 객체를 의미>
var myObj1 = {
a:"myObj1",
method1 : function(){
document.write(this.a + "<br>"); // myObj1
}
} ;
var myObj2 = {
a:"myObj2",
method1 : function(){
document.write(this.a + "<br>"); // myObj2
}
} ;
var a = "window" ;
document.write(this.a + "<br>"); // window
function kkb(){
document.write(this.a + "<br>");
}
kkb() ; // window
kkb.apply(myObj1) ; // myObj1  임의기능을 사용하여 객체의 주인을 변경한다
kkb.call(myObj2) ; // myObj2  임의기능을 사용하여 객체의 주인을 변경한다
myObj1.method1() ; // myObj1
myObj2.method1() ; // myObj2
62
Execution Context Stack
 This 위임기능
. Function.prototype 이 지닌 method (apply, call) 를 이용 : 위임기능 이라 하며, this 를 임의적으로 명시하기 위함이다
. 즉, function execution context stack 에서 this 를 임의적으로 변경(명시) 한다
window
객체
Function.
prototype
Kkb()
kkb.apply(myObj1,args)
This = window This = myObj1
<this 의 위임, window  myObj1 >
var myObj1={a:"myObj1"} ;
var myObj2={a:”myObj2”} ;
var a = "window" ;
document.write(this.a + "<br>"); // window
function kkb(){
document.write(this.a + "<br>");
}
kkb() ; // window
kkb.apply(myObj1) ; // myObj1
kkb.call(myObj2) ; // myObj2
kkb() ; // window
< apply / call 의 차이>
function sum(){
var result=0,
n;
for(n=0;n<arguments.length;n++){
result+=arguments[n];
}
this.result=result;
}
var sumA={result:0};
var sumB={};
// apply -> arguments 로 호출
sum.apply(sumA, [1,2,3,4,5,6,7,8,9]);
document.write(sumA.result + "<br>"); // 45
// call -> parameter를 개별로
sum.call(sumB, 1,2,3,4,5,6,7,8);
document.write(sumB.result + "<br>"); // 36
63
디자인 Pattern
 패턴이란 : 모범적인 관행, 쓰임새에 맞게 추상화 된 원리, 어떰 범주의 문제를 해결하는 template
 모듈화 (namespace)
. 전역객체를 최소화 하고, 객체를 기능별, 목적 별로 모듈화 하기 위하여 tree 화 시킨다
 싱글톤 패턴
. 원 의미는 특정 클래스의 Instance 를 오직 하나만 사용하는 패턴을 의미한다
. 적용방법
1) 일반객체의 성격상 그대로 사용하면 싱글톤 이 된다 (var myObj2 = new myObj1 이 불가능한 특징을 이용한다)
2) 생성자함수 를 변형 : Constructor 행위가 한번 만 이루어지게 조작한다
MYAPP
Module1 Module2 Module3
Interface1 Interface2 Interface3
MYAPP = {} ;
MYAPP .Module3= {} ;
MYAPP .Module3.Interface3 = function() {} ;
function myFunction1(a){
if (typeof myFunction.instance == “object”)
return myFunction.instance ;
this.a = a ;
myFunction.instance = this ; // static property
}
64
디자인 Pattern
 Factory 패턴
. 객체생성 대리인 역할을 하는 것으로서, new 를 사용하지 않고 객체가 지닌 Static 메소드에 객체생성을 요청하는 것이다.
. 원래 Java 에서는 타입을 모르고서도 객체생성을 요청하는 패턴을 의미한다
. 아래의 예제에서, 동일한 모델이면 동일한 객체를 사용토록 응용하는 Factory 패턴을 사용하였다
function Car(model,color){
this.model = model ;
this.color = color ;
}
Car.models=[] ;
Car.instances=[] ;
Car.factory = function(model,color){// STATIC 메소드
var factory ;
for(var i=0 ; i < Car.models.length ; i++){
if(Car.models[i] == model){
document.write("Already Instanced"+ "<br>");
return Car.instances[i] ;
}
};
document.write("New Instances=" + Car.models.length + "<br>");
Car.models[Car.models.length] = model ;
factory = new Car(model,color) ;
Car.instances[Car.models.length] = factory ;
return factory ;
};
var a = Car.factory("sonata","black") ;
var b = Car.factory("sonata","black") ;
var c = Car.factory("k7","black") ;
if(a==b) // 실제이리 되지않고, 개념적이다
document.write("Same Instance"+ "<br>");
65
디자인 Pattern
 퍼사드 (Facade) 패턴
. 원래의 의미는 App 의 편리성을 위하여 여러 객체 들의 method 를 하나의 통합된 method 로 구성 하는 것을 의미한다
. New 가 가능하지 않는 object (주로 plug-in) 에 대하여 interface 를 두어서 App 에서 접근하게 하는 방법이며,
이런 Interface 를 wrapper 라 하며, 생성자함수 객체로 구성한다
Wrapper.js
Module = Module || {} ;
Module.interface = function(){} // Constructor
Module.interface.prototype.method = function(){} // API
Module.interface.prototype.onEvent = function(){} // Event
Plug-In
Object
Main.js
var intA = new Module.interface() // 객체생성
intA.onEvent = intOnEvent ; // Event
function intOnEvent() {}
. Using Object or Embedded Tag
. Private API dependent upon Browser
module.interfcae = function() {
var divNode = document.createElement("div");
divNode.id = ‘XXXXX_plugin';
divNode.innerHTML +="<OBJECT id='pluginObjectXXX' border=0 classid='clsid:SAMSUNG-INFOLINK-TV‘
style='opacity:0.0;background-color:#000000;width:0px;height:0px;'></OBJECT>";
document.body.appendChild(divNode);
pluginObjXXX = document.getElementById('pluginObjectXXX');
pluginObjXXX.Open (‘EMP-MODULE-NAME', '1.000', ' EMP-MODULE-NAME '));
}
module.interfcae.prototype.method = function() {
pluginObjXXX.Execute ('App1', '1.000', 'App1'));
}
pluginObjXXX.OnEvent (event,type) = function (){
module.interfcae.prototype.onXXEvent() ;
}
66
이벤트
 이벤트 란 : 특정 Object 에게 사용자 (혹은 서버 나 장치) 가 메시지의 도달이나 요청사항을 통지 하는것.
 이벤트 등록방법 - 4가지 방법
1) Document 내에 element 선언 시 해당되는 이벤트에 function 을 연결 시킨다
2) JS 내에서 해당되는 객체의 이벤트에 function 을 연결 시킨다 : * 이때 onclick 에 대한 property 가 define 되어진다, event 전달은 안된다
3) JS 내에서 Window.event 객체에게 listener 를 등록한다
4) Link element 가 지니는 “href” 에 java script 함수와 연결시킨다 ; button 없이 JS function 을 호출하고자 할때 사용
<script>
function myEvent1(event)
{
var try1 = document.getElementById("try1") ;
var try4 = document.getElementById("try4") ;
document.write(typeof try1.onclick + "<br>"); // function
document.write(typeof try1.name + "<br>"); // unknown
document.write(typeof try1.any + "<br>"); // unknown
document.write(typeof try4.onclick + "<br>"); // unknown
}
function myEvent2()
{ document.write("myEvent2" + "<br>");
}
function myEvent3(event)
{ document.write("myEvent3" + "<br>");
}
</script>
<body>
<p> My Event Test by Hungrok Kwon </p>
<button id="try1" onclick="myEvent1(event)">Try1 </button> // 방법1
<button id="try2" >Try2 </button>
<button id="try3" >Try3 </button>
<button id="try4" >Try4 </button>
<a href=“Javascript: myEvent1(event)” > Test </a> // 방법4
</body>
<script>
function window.onload() // 페이지 laod 후 최초로 불린다
{
var try2 = document.getElementById("try2") ;
var try3 = document.getElementById("try3") ;
try2.onclick = myEvent2 ; // 방법2
try2.onclick = myEvent2(event) ; // 방법2 but ERROR
try2.onAny = myEvent2 ; // No ERROR
try3.addEventListener(onclick,myEvent3(event)) ; // 방법3 - ERROR at IE
}
<script>
67
이벤트
 Event Propagation
. 특정 이벤트 (type) 가 발생하면, 동일한 event 에 대하여 상,하위 노드 간 에 순차적으로 이벤트가 발생한다
- 상위노드  하위노드 로 이벤트 진행순서를 capturing 이라 함,
- 하위노드  상위노드 로 이벤트 진행순서를 bubbling 이라 함, IE 스타일
. 하기 예와 같이 button-1 에서 onlclick 이 발생하면, button-1  div-2  div-1 순서로 event 가 발생한다
(동일한 노드 계층간에는 이벤트가 발생하지 않는다)
. 노드 간 event propagation 을 중지 하기위하여는 Event Object 가 제공하는 stopPropagation() 메소드를 이용할 수 있다
div-1
div-2
button-1 button-2 select
<script>
function myEvent1(){ alert (“Event1”) ; } ;
function myEvent2(){ alert (“Event2”) ; } ;
function myEvent3(){ alert (“Event3”) ; } ;
function myEvent4(Event){
alert (“Event4”) ;
event.stopPropagation() ;
} ;
function myEvent5(){ alert (“Event5”) ; } ;
<body>
<p> Event Propagation test by Hungrok Kwon </p>
<div id="div1" onclick="myEvent1()">
<div id="div2" onclick="myEvent2()">
<button id="try1" onclick="myEvent3()">Try1 </button>
<button id="try2" onclick="myEvent4()">Try2 </button>
<select id="sel1" onclick="myEvent5()"> </select>
</div>
</div>
</body>
68
이벤트
 Event 객체의 전달
. Event 가 발생하면 해당 Java Script 함수가 호출되면서 event 객체도 argument 로 전달된다
* event 등록방법 중 방법2는 event 객체를 argument 로 전달 할 수 없다.
< Event 객체 Properties >
. bubbles ; Returns whether or not an event is a bubbling event
. cancelable ; Returns whether or not an event can have its default action prevented
. currentTarget ; Returns the element whose event listeners triggered the event
. eventPhase ; Returns which phase of the event flow is currently being evaluated
. target ; Returns the element that triggered the event
. timeStamp ; Returns the time (in milliseconds relative to the epoch) at which the event was created 2
. type ; Returns the name of the event
function(){}Event
(onclick)
Event 객체
69
JS Library
 Library
. App. 개발의 편의성을 위하여 일종의 대리적인 Macro API 를 제공하는 Java Script 이다
. JQUERY, YUI, PROTOTYPE 등이 많이 사용되는 Library 들이다.
 JQUERY
. 다양한 선택자 를 기반으로 객체에 대한 Effect 효과, Animation 효과, AJAX 및 기타 기능을 가져 가는데 편리하다
. 자세한 내용은 여기서는 다루지 않고, 개념적인 것만 기술한다
CSS3
JQUERY
Lib
Style
EffectJava
Script
Event
JQUERY Event
$(선택자).method()
DOM
Objects
1.Effect 를 위한 메소드
: Hide, Show, Fade, Slide, Animate, Chaining
2. HTML 관련 메소드
(1) DOM Manipulating: text, html, val, attr, append, prepend, before, clone, after, remove, empty
(2) CSS Manipulating: add/remove/toggleClass, css
(3) Dimension : width, height, innerWidth, innerHeight, outerWidth, outerHeight
(4) 기타 :
3. Traversing
4. AJAX

More Related Content

What's hot

DDD 구현기초 (거의 Final 버전)
DDD 구현기초 (거의 Final 버전)DDD 구현기초 (거의 Final 버전)
DDD 구현기초 (거의 Final 버전)
beom kyun choi
 
MyBatis에서 JPA로
MyBatis에서 JPA로MyBatis에서 JPA로
MyBatis에서 JPA로
Dongmin Shin
 
Ksug2015 - JPA1, JPA 소개
Ksug2015 - JPA1, JPA 소개Ksug2015 - JPA1, JPA 소개
Ksug2015 - JPA1, JPA 소개
Younghan Kim
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012Daum DNA
 
Ksug2015 - JPA2, JPA 기초와매핑
Ksug2015 - JPA2, JPA 기초와매핑Ksug2015 - JPA2, JPA 기초와매핑
Ksug2015 - JPA2, JPA 기초와매핑
Younghan Kim
 
엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623
Yong Joon Moon
 
엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613
Yong Joon Moon
 
파이썬 병렬프로그래밍
파이썬 병렬프로그래밍파이썬 병렬프로그래밍
파이썬 병렬프로그래밍
Yong Joon Moon
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
Yong Joon Moon
 
파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403
Yong Joon Moon
 
[162] jpa와 모던 자바 데이터 저장 기술
[162] jpa와 모던 자바 데이터 저장 기술[162] jpa와 모던 자바 데이터 저장 기술
[162] jpa와 모던 자바 데이터 저장 기술
NAVER D2
 
Effective c++(chapter3,4)
Effective c++(chapter3,4)Effective c++(chapter3,4)
Effective c++(chapter3,4)문익 장
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기
Yong Joon Moon
 
자바야 놀자 PPT
자바야 놀자 PPT자바야 놀자 PPT
자바야 놀자 PPT
JinKyoungHeo
 
Java 변수자료형
Java 변수자료형Java 변수자료형
Java 변수자료형
Hyosang Hong
 
Java JPA
Java JPAJava JPA
Java JPA
Yonghoon Ji
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기
Yong Joon Moon
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivity
JinKyoungHeo
 
Software Architect day - 웹 프레임워크 종결 - metaworks3
Software Architect day - 웹 프레임워크 종결 -  metaworks3Software Architect day - 웹 프레임워크 종결 -  metaworks3
Software Architect day - 웹 프레임워크 종결 - metaworks3
uEngine Solutions
 
DDD로 복잡함 다루기
DDD로 복잡함 다루기DDD로 복잡함 다루기
DDD로 복잡함 다루기
beom kyun choi
 

What's hot (20)

DDD 구현기초 (거의 Final 버전)
DDD 구현기초 (거의 Final 버전)DDD 구현기초 (거의 Final 버전)
DDD 구현기초 (거의 Final 버전)
 
MyBatis에서 JPA로
MyBatis에서 JPA로MyBatis에서 JPA로
MyBatis에서 JPA로
 
Ksug2015 - JPA1, JPA 소개
Ksug2015 - JPA1, JPA 소개Ksug2015 - JPA1, JPA 소개
Ksug2015 - JPA1, JPA 소개
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012
 
Ksug2015 - JPA2, JPA 기초와매핑
Ksug2015 - JPA2, JPA 기초와매핑Ksug2015 - JPA2, JPA 기초와매핑
Ksug2015 - JPA2, JPA 기초와매핑
 
엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623
 
엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613
 
파이썬 병렬프로그래밍
파이썬 병렬프로그래밍파이썬 병렬프로그래밍
파이썬 병렬프로그래밍
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
 
파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403
 
[162] jpa와 모던 자바 데이터 저장 기술
[162] jpa와 모던 자바 데이터 저장 기술[162] jpa와 모던 자바 데이터 저장 기술
[162] jpa와 모던 자바 데이터 저장 기술
 
Effective c++(chapter3,4)
Effective c++(chapter3,4)Effective c++(chapter3,4)
Effective c++(chapter3,4)
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기
 
자바야 놀자 PPT
자바야 놀자 PPT자바야 놀자 PPT
자바야 놀자 PPT
 
Java 변수자료형
Java 변수자료형Java 변수자료형
Java 변수자료형
 
Java JPA
Java JPAJava JPA
Java JPA
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivity
 
Software Architect day - 웹 프레임워크 종결 - metaworks3
Software Architect day - 웹 프레임워크 종결 -  metaworks3Software Architect day - 웹 프레임워크 종결 -  metaworks3
Software Architect day - 웹 프레임워크 종결 - metaworks3
 
DDD로 복잡함 다루기
DDD로 복잡함 다루기DDD로 복잡함 다루기
DDD로 복잡함 다루기
 

Similar to Java script 강의자료_ed13

알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations
Chang W. Doh
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
Kim Hunmin
 
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
중선 곽
 
Web Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30thWeb Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30th
Chang W. Doh
 
Hacosa jquery 1th
Hacosa jquery 1thHacosa jquery 1th
Hacosa jquery 1th
Seong Bong Ji
 
웹기술 이해 (프론트엔드 기초)
웹기술 이해 (프론트엔드 기초)웹기술 이해 (프론트엔드 기초)
웹기술 이해 (프론트엔드 기초)
JoonHee Lee
 
Django를 Django답게, Django로 뉴스 사이트 만들기
Django를 Django답게, Django로 뉴스 사이트 만들기Django를 Django답게, Django로 뉴스 사이트 만들기
Django를 Django답게, Django로 뉴스 사이트 만들기
Kyoung Up Jung
 
엄준일 04일차 HTML/Javascript 교육
엄준일 04일차 HTML/Javascript 교육엄준일 04일차 HTML/Javascript 교육
엄준일 04일차 HTML/Javascript 교육준일 엄
 
Ruby on Rails와 함께 하는 애자일 웹 개발
Ruby on Rails와 함께 하는 애자일 웹 개발Ruby on Rails와 함께 하는 애자일 웹 개발
Ruby on Rails와 함께 하는 애자일 웹 개발
Sukjoon Kim
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web Components
EunYoung Kim
 
자바 웹 개발 시작하기 (4주차 : MVC)
자바 웹 개발 시작하기 (4주차 : MVC)자바 웹 개발 시작하기 (4주차 : MVC)
자바 웹 개발 시작하기 (4주차 : MVC)
DK Lee
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)
연웅 조
 
컴포넌트 관점에서 개발하기
컴포넌트 관점에서 개발하기컴포넌트 관점에서 개발하기
컴포넌트 관점에서 개발하기
우영 주
 
[DevOn 2013] Backbone.js로 능동적 M-V 디자인 구현하기
[DevOn 2013] Backbone.js로 능동적  M-V 디자인 구현하기[DevOn 2013] Backbone.js로 능동적  M-V 디자인 구현하기
[DevOn 2013] Backbone.js로 능동적 M-V 디자인 구현하기
Gyutae Jo
 
3-2. selector api
3-2. selector api3-2. selector api
3-2. selector api
JinKyoungHeo
 
[week14] Getting started with D3.js
[week14] Getting started with D3.js[week14] Getting started with D3.js
[week14] Getting started with D3.js
neuroassociates
 
Django View Part 1
Django View Part 1Django View Part 1
Django View Part 1
Joong Hyeon Kim
 
ReactJS로 시작하는 멀티플랫폼 개발하기
ReactJS로 시작하는 멀티플랫폼 개발하기ReactJS로 시작하는 멀티플랫폼 개발하기
ReactJS로 시작하는 멀티플랫폼 개발하기
Taegon Kim
 
React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기
WebFrameworks
 

Similar to Java script 강의자료_ed13 (20)

알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
 
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
 
Web Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30thWeb Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30th
 
Hacosa jquery 1th
Hacosa jquery 1thHacosa jquery 1th
Hacosa jquery 1th
 
웹기술 이해 (프론트엔드 기초)
웹기술 이해 (프론트엔드 기초)웹기술 이해 (프론트엔드 기초)
웹기술 이해 (프론트엔드 기초)
 
Django를 Django답게, Django로 뉴스 사이트 만들기
Django를 Django답게, Django로 뉴스 사이트 만들기Django를 Django답게, Django로 뉴스 사이트 만들기
Django를 Django답게, Django로 뉴스 사이트 만들기
 
엄준일 04일차 HTML/Javascript 교육
엄준일 04일차 HTML/Javascript 교육엄준일 04일차 HTML/Javascript 교육
엄준일 04일차 HTML/Javascript 교육
 
7. html5 api
7. html5 api7. html5 api
7. html5 api
 
Ruby on Rails와 함께 하는 애자일 웹 개발
Ruby on Rails와 함께 하는 애자일 웹 개발Ruby on Rails와 함께 하는 애자일 웹 개발
Ruby on Rails와 함께 하는 애자일 웹 개발
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web Components
 
자바 웹 개발 시작하기 (4주차 : MVC)
자바 웹 개발 시작하기 (4주차 : MVC)자바 웹 개발 시작하기 (4주차 : MVC)
자바 웹 개발 시작하기 (4주차 : MVC)
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)
 
컴포넌트 관점에서 개발하기
컴포넌트 관점에서 개발하기컴포넌트 관점에서 개발하기
컴포넌트 관점에서 개발하기
 
[DevOn 2013] Backbone.js로 능동적 M-V 디자인 구현하기
[DevOn 2013] Backbone.js로 능동적  M-V 디자인 구현하기[DevOn 2013] Backbone.js로 능동적  M-V 디자인 구현하기
[DevOn 2013] Backbone.js로 능동적 M-V 디자인 구현하기
 
3-2. selector api
3-2. selector api3-2. selector api
3-2. selector api
 
[week14] Getting started with D3.js
[week14] Getting started with D3.js[week14] Getting started with D3.js
[week14] Getting started with D3.js
 
Django View Part 1
Django View Part 1Django View Part 1
Django View Part 1
 
ReactJS로 시작하는 멀티플랫폼 개발하기
ReactJS로 시작하는 멀티플랫폼 개발하기ReactJS로 시작하는 멀티플랫폼 개발하기
ReactJS로 시작하는 멀티플랫폼 개발하기
 
React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기
 

Java script 강의자료_ed13

  • 1. HR Kwon (hungrok@hanmail.net , khr2@samsung.com) IT 강의자료 Java Script 핵심개념 (Core Concepts)
  • 2. 1 머리글  HTML5 의 대중화 와 함께 Java Script 는 단순히 페이지를 동적으로 만든다는 초기 적용범위 에서 벗어나, 진정한 Web Application 을 위한 도구로 활용성이 증대되고 있다. C 와 Java 를 경험해본 Software 개발자 이면 비슷한 것으로 간주하여 JS 가 지닌 핵심적인 개념을 충분한 이해없이 사용 할 것으로 짐작하여 본다. 원서로 된 여러 훌륭한 책 들이 있지만, 공부하면서 이해한 핵심적인 부분을 원 자료의 일부 인용과 병행하여 필요한 분 들과 공유 하고자 한다. 2013년 12월, Hungrok Kwon  목차 . What is Java Script . HTML5 . Java VS Java Script . 변수 . 객체 . 함수일반 . 함수 – 객체화 및 상속 . 함수 - CLOSUE . Execution Context Stack . 디자인 Patterns . 이벤트 . Library Edition 1.0 2013.12 1.1 2014.07 1.2 2014.12 1.3 2015.05
  • 3. 2 What is Java Script  Web 의 3요소 : HTML document, CSS, JS  Web 페이지를 동적으로 만들고자 일련의 행위를 진행하기 위한 MVC (Model-data, View, Controller) 모델이다 < Tag , Element, Object > . Tag 란 각 element 의 대표 속성을 지칭한다 (예. 사람, 호랑이, 비둘기,,,) . Element 란 Tag 로 정의된 대표 속성을 지닌 개별 자 를 지칭한다 (예.사람-홍길동, 사람-이순신,,) . 각 Element 는 문서내의 독립된 객체이다 . Node 란 객체 간의 상하 (부모 자식 형제) Tree 구조를 나타낸다 <표현적 Markup> . 문서의 Layout 과 디자인 을 정의 . CSS3 features - Transform/Transition/Animation HTML5 Document Style Rule Java Script Style Effect Event Render Tree Display <구조적 Markup> . Head {}, Body{}, Script{} , Style{} . Tag (Element  Object) . New 29 tags in HTML5 : canvas, audio, video DOM (Node Tree) Effect CSS Document
  • 4. 3 What is Java Script  일련의 행위란 특정한 객체 (Object) 와의 연동을 의미하며, Event 로 부터 시작한다  객체는 크게 미리 만들어진 Object (Reference Object) 와 JS 가 스스로 생성한 객체 로 분류할 수 있다  Reference Object 은 5가지로 분류할 수 있다 : * Element 와 Event 는 실제 적으로는 Window 하부객체이다  Embedded Object 은 표준에서 지원하지 않는 Object 으로서 browser 에 built-in 되거나 (window.objA) 혹은 Plug-in (<OBJECT> 과 <embed> 태그로 reference ) 하여 사용한다. Reference Objects Java Script Create Objects Event Internal Devices Server document . Native embedded : Array, Object, Function, Date, Math,,,, . Browser : Window, Navigator, Screen, History, Location . Core DOM : Document, Element, Attribute, Event . HTML DOM elements : each elements in document . Others : Library, Embedded Objects (Plug-In) . Object (일반객체) . Function (함수객체) . Others : String, Date, Array IP (http) document.write Element.innerHTML Data Processing GFX, Media, console.log
  • 5. 4 What is Java Script  즉, JS 는 특정 Object 의 Property 를 상황에 맞추어 변경 하고자 함이 목적이다  JS 가 Reference Object 을 접근하기 위하여 해당 Object 을 지정하는 방법은 세가지 이다 1) DOM 이 지니고 있는 attribute 를 이용하여 찾아낸다 : x = document.getElementById(“main”) / x.getElementsByTagName(“p”) / getElementsByClassName(“classcar”) 2) DOM 이 지니고 있는 Node List 를 이용하여 찾아낸다 : Parent, Child,, 3) Event.target 을 이용한다 (Event 객체의 target 이 해당 Object 을 지칭한다, event.targetElement)  JS 에 의하여 Reference Object 은 동적으로 추가 가 가능하다 Reference Objects Java Script Event < W3C 에서 규정해놓은 Object 이 지니는 Properties > (1) Global Attributes : 공통적으로 지닌 것 (id, name, class, style,,,) (2) Attributes : 각 tag 별 (value,,) (3) Event Attributes : Event type 을 의미한다 (4) Methods : function(){} * Attributes 는 실제 define 이 되기전까지는 객체에 존재하지 않는다 : JS 객체의 속성을 지니는 관계이며, 동적으로 생성된다 (이벤트 페이지 참조) * style 은 CSS 가 관장하는 속성 값들이다 (이것을 통하여 CSS 를 effect 시킨다) * value 는 특정한 element 들만 지닌다 (input) Java Script Object 접근 <ul id="myList"> <li>Coffee</li> <li>Tea</li> </ul> function myFunction() { var node = document.createElement("LI"); var textnode = document.createTextNode("Water"); node.appendChild(textnode); document.getElementById("myList").appendChild(node); } 동적추가
  • 6. 5 What is Java Script  Java Script 에 의한 Web 페이지를 동적으로 만드는 예 . Tag 에 의하여 페이지에서 element 는 정의되고, 모든 element 는 Java Script 가 reference 하는 객체로 된다 . 해당 Element 가 지닌 속성 (Attribute 라 한다) 중 event attribute 에 Event Listener 역할을 하는 Java Script 함수를 연결한다 . 해당객체에 Event 가 발생하며, JS 의 특정 함수가 호출 (Invoke or Activate) 된다 . Image Object 의 소스를 변경하거나 사이즈를 확대한다 Image Object < Attributes > . ID, Name, Class . onclick = myFunction() ; Deliver the Event to JS JS Function Button Objects < 원래 Attributes > . ID, Name, Class . Width, Height . Source = URL-A BROWSER (WebKit) Event function myFunction (event) { ; } Which Object Event User Event Change The Source as URL-B
  • 7. 6 What is Java Script  Java Script 에서 CSS 객체를 접근하는 방법 Static code 이외에, 아래와 같이 동적으로 접근하는 두 가지 방법이 있다 (1) DOM 내의 특정 Element 객체 가 지닌 “style” attribute 를 통하여 접근 : element.style.display = block ; (2) Style Tag (<style>) 가 지닌 style 객체를 통하여 접근 * document 가 지니는 default CSS 객체에 의하여 특별한 지정이 없이 style 은 적용된다 (1) (2) <style id=“s1” > </style> var s1 = document.getElementById (“s1”) ; var sheet = s1.styleSheet ; var ruleset = sheet.cssRules ; // 룰셋에 새로운 빈 룰을 0 번째 룰로 추가한다 sheet.insertRule (‘p{}’,0) ; // 0 번 룰을 가져온다 var rule = ruleset[0] ; // 룰의 스타일 객체에 직접쓴다 rule.style[“margin”] = “10px 0” ; cssStyleDeclration 객체 DOM Element style styleSheet 객체 style TAG cssRules[ ] 객체
  • 8. 7 HTML5  Webkit Rendering * Web Engine : Webkit (Safari, Chrome), Gecko (Moziila-FireFox), Tridant (IE), Opera * Render tree 기준은 Frame 이다  Rendering is effected by CSS property * Parent element 가 display:none 으로 되면 하위 element 도 display:none 이 된다 * The GC (garbage collection) conditions are : Removed in DOM and Render Tree AND free reference CSS Property DOM Tree Render Tree Transparency Value display:none O X - display: none/inline/block visibility:hidden O O 0% visibility: hidden/visibility/inherit/collapse HTML PARSER CSS PARSER DOM Tree Attachment HTML Style Sheet Style Rules RENDER Tree Layout GFX Context
  • 9. 8 HTML5  HTML5 에서 신규로 지원되는 Reference Object 들에 대한 개략적인 소개이다 1. document.getelementByClassName . 기존의 ID, Name 에서 확장하여 Class 명으로 해당되는 Elements List 를 구하며, Object 을 Reference 하기 위함이다 . ID 와 Name 은 element 들이 고유하게 가져야 하는 정보이나 class 는 여러 element 를 지칭 할 수 있다 2. Web Storage : Client side (Browser) data base 기능을 의미한다. 3. Web SQL Data Base : Browser 내장 data base 에 SQL 을 통해 질의하는 API 이다 4. Web App Cache API 5. Web Worker . 웹 어플리케이션이 주 문서와 병렬적으로 Script 를 백그라운드로 수행할 수 있게 한다 . Thread 기반 메시지 처리 이다. 6. Web Socket . 서버와 IP 통신을 하기 위한 Client 용 TCP socket 개념의 API 이다 (socket, send, recv) 7. Navigator.getlocation
  • 10. 9 HTML5  Window (tab 단위로 불린다) - 하나의 Window 는 하나의 frame 과 하나의 document 를 지닌다 - iframe (inline frame) 태그는 Child window 가 생성되며, 두 window 가 하나의 frame 을 사용하는 개념이다 (render tree 는 Frame 기준이다) - Link 태그는 동일한 하나의 Window 내에서 새로운 document 로 대체(replace) 되는 것이다 (Attribute 을 통하여 새로운 Window 와 새로운 Frame 을 사용하는 Link 도 가능하다) - 동일한 Window 내에서 Linked 되어진 document 들 간에 forward, previous 기능이 가능하다 Window-Main (daum.net) Document-Main Frame A Frame 이란 보여지는 틀 이다 Window-Main (naver.net) Document-Main Frame A Window-Child (naver2.net) Document-Sub Window-Main (daum.net) Document-Main Frame A Document-A Document-B Link Link W3school.com 에서 Practice 도 상기 iframe 을 이용한다 . 좌측 (Practice) : sub document 를 작성한다 . 우측 (결과) : iframe 의 위치
  • 11. 10 HTML5  HTML5 에서 TAG 종류이다 종류 Description 선언 과 구조 Sectioning Heading / Footer Content Grouping Link Phrase elements Style Formatting Change Tracking List Table Form Embedded content Metadata Interactive content Scripting <html> <head> <body> <block_quote> <body> <details> <fieldsec> <td> <figure> <article> <nav> <aside> <section> <header> <h1~h6> <hgroup> <footer> <block> <quote> <div> <hr/> <br/> <span> <wbr/> <pre> <figure> <a> <area> <link> <abbr> <cite> <code> <dfn> <em> <figcaption> <u> <var> <kbd> <mark> <g> <s> <samp> <strong> <sub> <sup> <time> <b> <i> <pre> <small> <u> <style> <bdo> <bdi > <rp> <rt> <ruby> <ins> <del> <ol> <ul> <li> <de> <dt> <dd> <table> <caption> <colgroup> <col> <thead> <tr> <tu> <tfoot> <tbody> <td> <form> <button> <fieldset> <input> keygen> <label> <meter> <datalist> <audio> <video> <canvas> <embed> <source> <track> <figure> <figcaption> <iframe> <img> <mathml> <object> <paran> <svg> <base/> <command/> <link/> <meta/> <style> <title> <a> <button> <command> <details> <keygen> <label> <map> <menu> <select> <sumary> <script> <noscript> Deprecated in HTML5 <frame> <font> <div> <big> <acromym> <applet> <strike> <tt> Private marquee (IE)
  • 12. 11 HTML5  HTML 5에서 규정된 Event Type 종류이다 (편의상 Media 및 CSS3 Animation 관련 event 는 제외한다) 종류 Event Type New Description Mouse onclick ondbclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onscroll - - New New New New New New New - - - - - New New Fires on a mouse click on the element Fires on a mouse double-click on the element Script to be run when an element is dragged Script to be run at the end of a drag operation Script to be run when an element has been dragged to a valid drop target Script to be run when an element leaves a valid drop target Script to be run when an element is being dragged over a valid drop target Script to be run at the start of a drag operation Script to be run when dragged element is being dropped Fires when a mouse button is pressed down on an element Fires when the mouse pointer moves over an element Fires when the mouse pointer moves out of an element Fires when the mouse pointer moves over an element Fires when a mouse button is released over an element Script to be run when the mouse wheel is being rotated Script to be run when an element's scrollbar is being scrolled Key Board onkeydown onkeypress onkeyup - - - Fires when a user is pressing a key Fires when a user presses a key Fires when a user releases a key Form onblur onchange oncontextmenu onfocus onformchange onforminput oninput oninvalid onslect onsubmit - - New - New New New New - - Fires the moment that the element loses focus Fires the moment when the value of the element is changed Script to be run when a context menu is triggered Fires the moment when the element gets focus Script to be run when Script to be run when a form gets user input a form changes Script to be run when an element gets user input Script to be run when an element is invalid Fires after some text has been selected in an element Fires when a form is submitted Window onload onunload onstorage onpopstate - - New New Fires after the page is finished loading Fires once a page has unloaded (or the browser window has been closed) Script to be run when a Web Storage area is updated Script to be run when the window's history changes
  • 13. 12 HTML5  구조적 표현을 처리하는 CSS 에 대한 개략적인 개념이다 . 선택자 (Selector) 란 어느 element 를 지칭하는가를 지정하는 script 이며, 개별 혹은 복수개의 element 가 선택된다 . JS 에서도 동적으로 CSS properties 를 변경시킬 수 있다 : getElementById().style.propertie Java Script Properties selector < Basic Properties> . Background . Color . Text , Overflow . Font . Positioning . Display / visibility . Box /Margin/Boarder/Padding . List style . Table . Column . Grid . Linebox < CSS3 Properties> . 2D/3D transform . Transition . Animation < Advanced Properties> . Hyperlink . Generated Content . Marquee (Text 흐름) . Content for paged media . Paged Media . Print . Ruby . Speech . User Interface . @media . @font-face . @keyframes Elements < Selector 적용방법> 1) 선택자 : *(전체) / element (특정 element 전체) / # (특정ID) / . (특정 class) 2) 선택자 조합 div,p ; Selects all <div> elements and all <p> elements div p ; Selects all <p> elements inside <div> elements div>p ; Selects all <p> elements where the parent is a <div> element div+p ; Selects all <p> elements that are placed immediately after <div> elements 3) 의사: 특정 element 에 대한 상태 및 node 순서에 따른 선택 (element:상태) a: link/visited/active/hover input: focused/enabled/disabled/checked p: first-letter/first-line/before/after/lang p: first-of-type/last-of-type/only-of-type/nth-of-type/nth-last-of-type p: first-child/only-child/nth-child/nth-last-child/last-child 4) 특정 element 가 지니는 attribute [attribute] 의 속성값을 지닌것. [attribute] [attribute = value ] ; = / ~= / |= element[attribute ^=value] ; ^= / $= /*= <style> ~ </style>
  • 14. 13 HTML5  CSS Box Model . HTML 의 모든 element 는 Box 형태로 간주된다 (Render 적 관점) . DIV 을 예로 들어 기본적인 CSS Property 를 지정하면 아래와 같다 div { position: fixed ; width: 300px; height : 300px ; left : 20px ; top : 20px ; padding: 25px; border: 25px solid navy; margin: 25px; background-color: #00ff00; background-image: url("img_tree.png"); background-repeat: no-repeat; background-position: right top; display: block ; }
  • 15. 14 HTML5  CSS3 Animation Property Java Script 를 이용하지 않고, CSS3 속성으로 Render 객체 대상을 동적으로 변화 시키고자 함 이며, 주로 GPU 를 사용한다 1) Transform (-webkit-transform: rotate) . 회전(Rotate), 비틈(Skew), 확대/축소(Scale), 이동(Translate) . 2D는 회전 시 시계방향 또는 반 시계 방향으로 회전을 시킨다면, 3D는 좌우, 위아래, 앞뒤로 움직임을 줄 수 있다. 2) Transition (-webkit-transition: ) . 객체가 지닌 CSS Property (하나 혹은 다수)을 변경할 때, 속성이 변경되는 속도 를 조절하는 목적이다 . webkit-transform 도 지정 가능한 Property 에 해당된다 . Property, Delay, Duration, Timing-function 4가지 세부속성을 지닌다 3) Animation : -webkit-animation : myAnimation 5s linear infinite @-webkit-keyframes myAnimation { // keyframe 0% {background: red; left:0px; top:0px;} // background 대신에 webkit-transform 을 줄 수 있다 25% {background: yellow; left:200px; top:0px;} 50% {background: blue; left:200px; top:200px;} 75% {background: green; left:0px; top:200px;} 100% {background: red; left:0px; top:0px;} } #myID { // 세부 property 지정 -webkit-animation-name:myAnimation; /* 키프레임의 이름을 지정합니다 */ -webkit-animation-duration:2s /* 애니메이션의 총 길이를 시간으로 지정합니다. 2s는 2second(=2초) 입니다. */ -webkit-animation-timing-function:ease /* 타이밍 펑션을 지정합니다. ease는 처음과 끝을 부드럽게 합니다 */ -webkit-animation-iteration-count:infinite/*반복횟수를 지정합니다. infinite는 무한반복입니다. */ -webkit-animation-direction:normal /*방향을 지정합니다. normal은 정방향으로 진행합니다 , reverse, alternate, alternate-reverse */ -webkit-animation-play-state:running /*애니메이션의 진행 상태 입니다. running, paused*/ -webkit-animation-delay:0s /*애니메이션의 시작전 지연시간을 지정합니다. */ } <animation-timing-function의 값> ease -> 시작과 종료를 부드럽게 합니다. linear -> 모든 애니메이션이 일정한 간격으로 작동합니다. ease-in -> 서서히 시작합니다. ease-out -> 서서히 종료됩니다. ease-in-out -> 서서히 시작하여 서서히 종료됩니다. cubic-bezier(x1,y1,x2,y2) -> 3차원 배지어(bezier) 곡선의 값을 직접 입력하여 진행합니다.
  • 16. 15 HTML5  CSS3 Animation 개념 . 해당 Animation 의 Thread 가 생성되어 시나리오 에 맞추어 CSS property 를 변경할 것 으로 추정 Element Object Scenario Option @Keyframes{ // 시나리오 틀 이다 step(x %) {actions} step(x %) {actions} step(x %) {actions} step(x %) {actions} } * Actions 는 CSS property 를 의미한다 (예: position, color, transform ,,,) * from == step 0 % to == step 100 % . 시나리오 단위시간 . 동작모드 . Loop Count . 방향 Animation Thread
  • 17. 16 HTML5  Sample of CSS3 Animation CSS 에 있는 Marquee Property 를 사용치 않고, GPU 를 사용하기 위하여 Animation 과 Transform 을 이용하여 Text 흐름을 구현한 예 이다 this.setMarquee = function( option ) { // option.target : 마퀴 적용 할 태그 // option.title : 마퀴 적용할 태그 안에 제목 문자열이 들어있는 태그 ( <a> tag ?) // option.fontSize : 마퀴 대상의 width와 제목 문자열의 width를 비교해서 제목 문자열의 width가 더 길 때만 마퀴를 적용하는데 이 때 비교에 사용할 제목 문자열의 폰트 크기 // option.fontWeight : 폰트 두께 지정 // option.animationRuleName : 애니메이션 룰에 사용할 이름. // option.condition : 기본적으로 canvas 태그를 이용해 text의 넓이를 구한 후 부모 객체의 넓이와 비교하여 넓이를 구하지만, dm condition 항목을 통해 추가 조건을 넣을 수 있음. var self = this; if( !option.fontSize ) option.fontSize = 20; if( typeof option.fontSize === 'number' ) option.fontSize += 'px'; if( !option.fontWeight ) option.fontWeight = ''; if( !option.animationRuleName ) option.animationRuleName = 'home-menu-marquee'; clearTimeout( this.marqueeTimeoutId ); this.marqueeTimeoutId = setTimeout( function() { var width = option.target.width(), text = option.title.text().trim(), txtWidth = self.getTextWidth( option.title.text().trim(), option.fontSize + ' ' + option.fontWeight + ' YoonGothic770' ); // using Canvas measureText method if( parseInt( width ) - 10 <= parseInt( txtWidth ) || option.condition ) { var rule = option.animationRuleName + " {" + "0% { -webkit-transform:translateX(0px); opacity:1}" + "49% { -webkit-transform:translateX(" + ( parseInt( txtWidth +50 ) * -1 ) + "px);opacity:1}" + "49.0001% { -webkit-transform:translateX(" + ( parseInt( txtWidth + 50 ) * -1 ) + "px);opacity:0}" + "49.0002% { -webkit-transform:translateX(" + parseInt( txtWidth + 50 ) + "px);opacity:0}" + "49.0003% { -webkit-transform:translateX(" + parseInt( txtWidth + 50 ) + "px);opacity:1}" + "100%{ -webkit-transform:translateX(0px); opacity:1} }"; if( self.style.cssRules.length != 0 ) self.style.deleteRule( 0 ); self.style.insertRule( "@-webkit-keyframes " + rule, 0 ); option.title.addClass( 'start' ); option.title.css( { text-overflow' : 'clip', ‘ overflow' : 'visible', '-webkit-animation' : option.animationRuleName + ' ' + ( text.length * 500 ) +'ms linear infinite', 'width' : ( txtWidth + 100000 ) + 'px', 'text-align' : 'left' } ); } else { option.title.removeClass( 'start' ); option.title.css( { 'text-overflow' : 'ellipsis', 'overflow' : 'hidden', '-webkit-animation' : '' } );
  • 18. 17 HTML5  Interaction with Server . 서버에 data 를 요청하거나, 보내거나 혹은 특정한 작업 (ASP,PHP) 을 요청하는 client 의 동작은 4가지로 분류 할 수 있다 . Performed by LOADER in Webkit * URL 은 Local File system 접근도 가능하다 * 한번 Retrieve 한 Data (document, file, image ) 는, Webkit 내부에 cached 되어지며 (특정한 버퍼의 용량이 부족하면 Update), Cache 를 사용하지 않고 새로이 retrieve 하기 위하여는 다음 장 의 Bypassing the cache 를 참고한다, < Java Script> window.webSocket() TCP/IP 서버 (Web Socket Server) send() / recv() < Java Script> window.XMLHttpRequest() TCP/IP 서버 (Web Server) http get/post < Element in HTML> <form> action=“” TCP/IP 서버 (ASP/PHP Server) http post/get < Element in HTML> <a> href=“url” <xxx> src = “url” TCP/IP 서버 (Web Server) http get
  • 19. 18 HTML5  Bypassing the cache A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example: http://foo.com/bar.html  http://foo.com/bar.html?12345 http://foo.com/bar.html?foobar=baz  http://foo.com/bar.html?foobar=baz&12345 Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache. You can automatically adjust URLs using the following code: var oReq = new XMLHttpRequest(); oReq.open("GET", url + ((/?/).test(url) ? "&" : "?") + (new Date()).getTime(), true); oReq.send(null);
  • 20. 19 HTML5  XHR (XMLHttpRequest) Object for AJAX < Java Script> window.XMLHttprequest() TCP/IP 서버 (Web Server) http get < Method > xhr = new XMLHttpRequest open ( METHOD, url, async) // GET,POST,HEAD send () // Null , XMLFile, Form , Text setRequestHeader(header,value) // overrideMimeType("text/plain; charset=x-user-defined"); // Handling binary data addEventListener ("progress", updateProgress, false); // progress,load,error,abort abort() < Event Callback > onload() onreadystatechange() ontimeout() < Attribute > readyState // 0,1,2,3,4 // 0 Uninitialized, 1 Loading, 2 Loaded, 3 Interactive, 4 Completed status // 200,403,404,500 for http status code from the server responseXML // xmldoc = hr.responseXML responseText // textstring = hr.responseText , normally UTF-8 timeout < XHR2 New Feature since 2012> < Attribute > responseType // “arraybuffer” “blob” “file” “formdata” response // arraybuffer = hr.response // with the responseType Xml,Text,Arraybuffer,,
  • 21. 20 HTML5  Link (a) Tag , connected to 1) another document, specified with URL, the window shall be same or new by attribute “target” 2) email 3) Java Script 4) Move View focus to specific element  Canvas TAG . Canvas 는 Graphics 를 위한 Container 이다 (Canvas == Container for graphics) . getContext(“2d” or “webgl” ) 를 통하여 얻어진 Canvas 객체에 Texture 를 그리는 작업이다 (webgl 은 3d 에 해당) . Texture 는 일반적인 Rectangle, Text, Path (line, polygon, circle) 과 Image 를 대상으로 하며, Transform 행위도 가능하다 Texture Fill Style . Color . Gradient . Pattern Stroke Style . Color . Gradient . Pattern < Rect create then draw> (방법1) createRect  fill or stroke (방법2) fillRect (방법3) strokeRect < Text create then draw> (방법1) fillText (방법2) strokeText < Path create then draw> . beginPath . stroke
  • 22. 21 HTML5  Plug-In . Plug-In 은 HTML5 에서 제공하는 표준적인 객체가 아닌 시스템 (Webkit) 의 Native 기능 과 연결되는 기능이다 . object 혹은 embed Tag 를 사용하여 시스템이 제공하는 Plug-in 사용을 명시한다 . 참고로 Web page 내의 Youtube 동영상 play 는 object 에서 iframe 으로 변경 되었다 html ActiveX NPAPI PPAPI Native Object object / embed ActiveX : MS IE 에서 사용 NPAPI : Webkit 계열에서 사용, (netscape plug-in API) Flash Player Applet 기타 (Security)
  • 23. 22 Java VS Java Script  Java 는 Programming Language 이며, JS 는 ECMA-262 를 기초로 하는 Script Language 이다  Java 는 Type check 가 엄격하며, 정적인 Class 를 기반으로 객체지향 (Instance 객체생성 과 상속) 한다 Instance 객체생성과 상속이 명확하게 구분되어 있다 (new 와 extend).  JS 는 Type check 가 느슨하며, 동적인 (객체의 변형이 가능함) 함수객체 (생성자 함수)를 기반으로 객체지향 한다 Instance 객체생성 과 상속이 명확하게 구분되어 있지 않고, 다양한 패턴을 활용한다  이래서 쉬운듯 어려운 것이 JS 이다 구분 객체생성 (new) 객체상속(extend) 멤버변수 Instance (독립된 멤버변수) 공유 및 확대 멤버 메소드 공유 공유, 확대 및 Overriding Class-A Class-B Class-C Class-D extend new new JAVA . 기본적으로 Constructor 는 Instance 화 되고 Prototype 은 공유 및 Overriding 한다 . 패턴에 따라 Constructor 만 Instance 시키고 Prototype 은 사용하지 않거나, 그 반대의 상속을 적용한다. 함수객체 Constructor Prototype 새로운 객체 new Java Script
  • 24. 23 Java VS Java Script  Instance 객체생성 과 상속을 Java 와 JS 간 비교하면 아래와 같이 정리할 수 있다 JAVA Java Script 객체생성 (new) 객체상속 (extend) 멤버 변수 Instance (독립된 멤버변수) 공유 및 확대 Instance 멤버 메소드 공유 공유, 확대 및 Overriding Instance Prototype 객체 (변수 와 메소드) - 공유
  • 25. 24 Java VS Java Script  소스 code 에서 부터 CPU 에 Instruction 되는 과정을 비교한다 Source (a.java) Compiler (javac) Byte Code (a.class) ByteCode Verifier Memory Class Loader Inter preter CPU Java JVM Source (a.js) JS Engine (Interpreter) MEMORY CPU Java Script
  • 26. 25 변수 (Variable)  특징 . 변수 란 특정한 data 를 지닌 공간을 의미하며, 이름을 지닌다 (var reference-name = value) . JS 는 Type check 가 약한 특징으로, data type 에 대하여 사전에 type 을 명기하지 않고 Assignment 과정에서 (a=x) 결정되며, 동적으로 변경이 가능한 특징을 지닌다 (Number 에서 Function 으로도 변경이 가능하다) . Primtive data type 이든 모든것은 객체 적 성격을 지닌다 : String, Date, Array [], Object {}, Function 들은 객체이다. * 실제 typeof 로 확인하여 보면 “object” 으로 보인다  jQuery.type() 을 사용하면 세부 type 알 수 있다 // Variable Types var a = 10 ; // number var b = 3.314 ; // number var c = true ; // boolean var d = "korea" ; // string var e = new Date() ; // object (* not date) var f = [] ; // object (* not array) var g = {} ; // object var h = /pattern/i // object (* not RegExp) var i = function(){} ; // function a = function(){} ; document.write(typeof a + "<br>"); // function // Variable Types var k =192; var y ; document.write(typeof y + "<br>"); // number y = k.toString() ; document.write(typeof y + "<br>"); // string var f = [“samsung”,”hyundai”} ; var x = f ; // x have a same value from f
  • 27. 26 변수 (Variable)  특징 . 변수가 생성되면 내장객체 (Browser가 제공하는) 의 prototype 을 자동으로 상속하여 공유한다 이것을 기반으로 prototype 이 제공하는 범용용도의 API 를 사용할 수 있다. ARRAY < Properties> : constructor, length < Prototype Methods> : concat, indexOf, join, lastIndexOf : pop, push , reverse, shift, slice, sort, : slice, toString, unshift, valueOf OBJECT < Properties> : constructor < Prptotype Methods> : hasOwnProperty : isPrototypeOf, propertIsEnumerable : toLocaleString : toString, valueOf FUNCTION < Properties> : constructor, prototype <Prototype Methods> : apply, call, bind : toString, valueOf STRING < Properties> : constructor, length, prototype < Prototype Methods> : charAt, charCodeAt , fromCharCode : concat, indexOf, lastIndexOf : localeCompare : match, replace, search, slice, split : substr, substring : toLowerCase, toUpperCase, toString : trim, valueOf Array. prototype Array Object. prototype Object Function. prototype Function String. prototype String Arguments. prototype Function 호출시 Arguments < Properties> : caller : callee : length
  • 28. 27 변수 (Variable)  특징 . 내장객체 사용방법 <String Method 사용 예> url += a.toString ; url = url.concat(“/temp/”) ; charCodeAt(); // return unicode from string <arguments 사용 예> var args = Array.slice(arguments);
  • 29. 28 변수 (Variable)  특징 . 접근영역 에 따라 전역변수 (Global Variable) 와 함수내의 Local Variable 로 분류할 수 있다 . 전역변수 는 메모리에 항상 상주하며, 어디서나 접근이 가능하다 . Local Variable 는 해당함수가 호출될때 메모리에 존재하고 종료되면 소멸되며, 해당 함수 내 에서만 접근이 가능하다 일반객체 . Property 함수객체 . Property 함수객체 . Property Window . Property 전역 Variable Local Variable 일반객체 . Property
  • 30. 29 변수 (Variable)  특징 . 일반객체들은 내부의 일반객체들을 포함하여 전역변수에 속한다 (예 참조. myObj1 – myObj2 ) . 함수객체내의 변수들은 기본적으로 local variable 이나, 선언방법에 따라 Static 으로 사용이 가능하다 - Local variable : 함수가 return 되면 메모리에서 소멸된다 - Static variable : Global 한 접근은 안되나, 함수가 return 되더라도 메모리에 남아있다 . 함수객체의 property 이나 함수 바깥에서 선언된것들은 전역영역 이다. var myObj1 = { abc : 10, myObj2 : {}, method1 : function() { document.write("First" + "<br>"); } } ; myObj1.myObj2.method2 = function() { document.write("Second" + "<br>"); myObj1.method1() ; } myObj1.myObj2.method2() ; < Result > Second First var h = function(init){ // Function (FE) var kka = 100 ; // Local if(init==true) kkb = 1 ; // Static (without var) else kkb++ ; document.write(kkb + "<br>"); //1,2,3,,, }; h.kkc = 300 ; // Global document.write(h.kka + "<br>"); // Undefined as Local document.write(h.kkb + "<br>"); // Undefined as Static h(true) ; // 1 h() ; // 2 h() ; // 3
  • 31. 30 변수 (Variable)  Object . Plain Object 이란 쌍 (key/value) 을 지닌 data 의 set 이다 . Object (일반객체 혹은 함수객체) 의 구성요소인 property 와 method 에 대한 추가 시 부여 방법은 아래와 같이 세 가지 방법이다 1) obj1.name = ; 2) obj1[0] = ; 3) obj1[“name”] = ; // obj1.name 과 동일하다  jQuery 에서 함수객체에 함수를 추가하는 방법으로 사용된다 * 함수도 Property 추가 시 상기 부여 방법이 동일하게 사용된다 (동적특성) * [0] 방법은 Closure - Memoization 패턴에서 많이 사용된다 var obj1={ a1:1 }; // Property 추가 obj1.a2=2 ; obj1.a3=function(){document.write("a3")} ; obj1[0]=function(){document.write("a0")} ; obj1["kk"]=function(){document.write("kk")} ; document.write(typeof obj1["a2"],obj1.a2) ; // number,2 obj1.a3() ; // a3 obj1[0]() ; // a0 obj1.kk() ; // kk obj1=obj1||{} ; // 기존에 있으면 유지하고, 없으면 객체 {} type 지정을 의미한다
  • 32. 31 변수 (Variable)  Array : . 내부요소에 대한 값만 지니며 이름 은 지닐 수 없고, 이름대신 [index] 를 사용 할 수 있다 var a=["kkk",1,"zzz"] ; // a[0] a[1] a[2] document.write(a.length + "<br>"); // 3 a[3] = "yyy" ; // 추가함 document.write(a.length + "<br>"); // 4 a.kka = 10 ; // 인정안됨 document.write(a.length + "<br>"); // 4
  • 33. 32 객체  객체 의 정의 . 포괄적 : 이름 과 값을 지닌 data (Property) 의 집합 및 data 를 조작하기 위한 Method 가 하나로 묶인 것 . Java Script 에서 객체란 : Property 의 집합 과 하나의 prototype object 을 지니고 있다 . Method : 특정함수가 저장된 객체의 Property 로 정의하며, 객체의 속성을 취득 및 변경 하기 위한 창구이다 객체의 프로퍼티에 할당되어 객체를 통해서 호출되는 함수를 메서드라 부른다. . 객체의 개념 모습  객체 는 재사용 을 위하여 객체생성 (Instance) 과 객체상속 이라는 Behavior 를 지닌다 . JS 에서 객체생성시 모든 객체는 내장객체 인 Object 객체에 상속된다 . 상속은 Property 에 대한 공유 와 확대를 위함이다 객체 (Object) Properties Methods Function(){} 사용자
  • 34. 33 객체  객체 의 생성 방법 : 세가지 로 분류된다 1) Literal 적 방법 : . var myObj1 = {} ; // 가장 일반적인 객체의 생성방법 (원시객체) 2) 생성자 를 이용 (new) : . var myObj2 = new Object() ; // 내장객체 를 이용, 권장하지 않는다 . var myObj3 = new FunctionObjA ; // 생성자 함수객체 (constructor function) 를 이용  가장 일반적인 Instance 생성 과 상속 방법 3) var myObj4 = Object.create(myObj1 ) . ECMA5 부터 지원되는 기능이며, IE Browser 에서는 아직 지원이 되지 않는다 . myObj4 는 함수객체이며, 일반객체를 함수객체가 상속하는 개념이다 *주1. var kkk = new myObj1 ; // 이런 경우 같이 기존의 객체를 이용하여 new 는 불가능 하다 (할 이유도 없을 것이다) *주2. var kkk = myObj1 ; // 이 경우에는 “kkk” 라는 object 이 생기는 것이 아니고 다만 “myObj1 ” 를 reference 할 뿐이라, “kkk” 는 “myObj1 ” 와 동일한 것이다.
  • 35. 34 객체  객체 에 구성되는 Property 는 생성시 사전에 정하거나 혹은 생성후 에 추가 할 수 있다 . 즉, 백지 인 객체만 만들어 놓고 필요할 때 추가할 수 있으며, 삭제 할 수 있다 (이를 동적인 특징이라 한다)  객체 내부의 Property 중 아래 두 가지는 구성이 불 가능 하며, 객체의 Property 는 전역영역으로 접근이 가능하다 . var 로 시작하는 variable . 선언함수 (FD) 및 자기호출함수 myObj3 = { a : 3, method1 : function() {} //var abc: 4, // ERROR // function method2() {} // ERROR // (function xyz() { }) (); // ERROR } ; alert(“myObj1.a) ; myObj1.method1() ; // Invoke // 생성시 Property 를 정한다 var myObj1= { a : 3 , b : “school”, method1 : function () {} // ; 추가하면 안됨 } ; delete myObj1.b ; // 삭제를 할 수도 있다 // 생성 후에 Property 를 추가한다 var myObj2 = {} ; myObj2={ a: 1, method1 : function() {document.write("aa")} // ; 추가하면 안됨 } // 개별형식으로 만 추가 myObj2.b = 2 ; myObj2.method2 = function () {document.write("bb")} ; //myObj2={} ; // 참고-이리하면 비어진 객체가 된다 myObj2=myObj2||{ // {} 방식으로 추가 c:3 } myObj2.method1() ; // aa myObj2.method2() ; // bb // defineProperty 를 이용한 생성 및 속성관리 방법 var myObj3 = {} ; Object.defineProperty(myObj3, prop1,,,)
  • 36. 35 객체  defineProperty . 객체의 특정한 Property 에 대하여 특정한 관리를 할 수 있다 < define 가능한 속성들> -able 들은 boolean 으로서 default false 값을 지닌다 value ; writeable ; value 를 변경가능여부 , value 를 선언 시 에만 가능 enumerable ; value 의 속성이 enumber 여부 set() ; setter Method, value 가 선언되면 사용 못한다 get() ; getter Method, , value 가 선언되면 사용 못한다 configurable ; set(), get() 과 함께 객체의 정의자체를 변경 하기 예제는 set, get 을 이용하여 하나의 property 에 multi function 을 구성한 예이다. Object.defineProperty(a={},"prop1",{value:1,writeable:true}) ; // a.prop1=1 Object.defineProperty(b={},0,{value:2,writeable:true}) ; // b[0]=2 document.write(a.prop1, b[0]) ; a.prop1 = 4 // b[0] = 5 ; document.write(a.prop1, b[0]) ; // still 1,2 (?) Object.defineProperty(c={},"prop1",{ set:function(arg){document.write("set“, arg)}, get:function(){document.write("get")}}) ; var k=c.prop1 ; // call get() c.prop1=2 ; // call set(), arg=2
  • 37. 36 객체  defineProperty . 하기 예제는 set, get 을 이용하여 하나의 property 에 multi function 을 구성한 예이다. var curWidget = curWidget || {}; Object.defineProperty(curWidget,'onWidgetEvent',{ set : function(arg0){ this._onWidgetEvent = this._onWidgetEvent || []; this._onWidgetEvent.push(arg0); }, get : function(){ return function(eventData){ var _onWidgetEvent = this._onWidgetEvent || []; for(var i=0,l=_onWidgetEvent.length;i<l;i++){ try { _onWidgetEvent[i](eventData); } catch(e) { } } }; } }); curWidget.onWidgetEvent = function(event){ console.warn("curWidget.onWidgetEvent add 1111 "); }; // widget event callback curWidget.onWidgetEvent = function(event){ console.warn("curWidget.onWidgetEvent add 2222 "); }; // widget event callback curWidget.onWidgetEvent = function(event){ console.warn("curWidget.onWidgetEvent add 3333 "); }; // widget event callback
  • 38. 37 객체  객체생성 시 기본 상속관계 . 객체 가 생성되면 아래와 같이 내장 객체인 Object.prototype 객체를 자동으로 상속(공유) 받는다 . “__proto__” 는 보이지 않는 내부 개념을 의미하는것으로 보인다  Object 내장객체 는 아래와 같은 세부 property 와 method 를 지닌다 var myObj1={} properties methods __proto__ Object 내장객체 properties methods prototype <Methods> . create() . defineProperties() . defineProperty() . freeze() . getOwnPropertyDescriptor() . getOwnPropertyNames() . getPrototypeOf() . is() . isExtensible() . isFrozen() . isSealed() . keys() . preventExtensions() . seal() . setPrototypeOf() < Properties> . prototype <Prototype Methods> . prototype.eval() . prototype.hasOwnProperty() . prototype.isPrototypeOf() . prototype. propertyIsEnumerable() . prototype. toLocalString() . prototype. toSource() . prototype. toString() . prototype. unWatch() . prototype. valueOf() . prototype. watch() < Prototype Properties> . prototype.__count__ . prototype.__noSuchMethod__ . prototype.__parent__ . prototype.__proto__ . prototype.constructor var myObj1={} ; document.write(myObj1.__proto__ + "<br>"); // undefeined document.write(myObj1.constructor + "<br>"); // function Object() (*** Object.prototype.constructor 의 내용이다) Object.prototype constructor Properties Methods
  • 39. 38 객체  객체 트리 . 모든 객체는 하부에 객체를 포함 할 수 있으며, 가장 상위의 객체는 window 내장객체 이다 . 해서, window 를 루트로 하여 객체 tree 가 형성된다 . 함수 호출시 Scope chain 이 형성되며, Execution Context Stack 에서 추가 설명한다 . objC 의 method 를 호출 시 FuncObjA.objC.method() , 즉 루트객체인 window 는 명기하지 않아도 된다 . 이러한 Tree 구조를 이용하여 큰 기능에 대하여 부분 기능별로 모듈화 설계가 가능하며 이를 name space 라 칭한다 전역영역 window objA FuncObjA FuncObjC objC FuncObjBobjB
  • 40. 39 함수  함수 란 . 일반 객체와 유사한 성질을 지닌 객체로서 First Class Object 이며, 실행 context stack 의 유효범위 (Scope) 를 제공한다 . 일반객체와 마찬가지로 자기자신의 property 와 메소드를 지니며, 특정객체를 하부에 포함 할 수 있다 . 생성자함수 는, 일반객체 의 new 대상이 되어 Instance 객체생성 과 상속이 되는 원형객체로 사용된다 . 상기와 같은 사유로, Java Script 는 함수를 기반으로 하는 객체지향 이라 할수 있다  차례 1) 함수 생성방법 2) 함수의 사용적 특징 3) 용도적 분류 4) 원형객체 로의 사용 (클래스 방식의 상속패턴) 5) CLOSURE 특성
  • 41. 40 함수  함수 생성방법 : 세 가지로 분류된다 1) 선언함수 (Function Declaration ) . function FunctionName () { } // 함수 invoke 시 FunctionName() ; 2) 표현함수 (Function Expression) . var referenceA = function () { } ; // 함수 invoke 시 referenceA() ; . 일반객체 나 함수객체 에 포함되는 내부함수도 이것으로 볼 수 있다 ; myObj1.method : function() {}; . var referenceA = new Function() 도 이것으로 볼 수 있으나, 사용이 권장되지 않는다 . var referenceB = referenceA 는 표현함수를 새로운 변수에 할당하는 것이다 *주1. 함수에 이름이 명기 되었다면 기명함수, 없다면 익명함수 로 불리나 이러한 구분은 실효적이지 못하다 *주2. 선언함수 와 표현함수 의 주요한 차이점 (거의 동일하게 사용된다고 보면 된다) 1) 특정한 상황에서 FD 는 불가능 한 경우 (즉 variable 형 만 가능하다) . 일반객체 내에서 구성되는 method 는 FD 는 불가능하고 FE 만 가능하다 (객체 설명 페이지 참조) . 자기호출함수 내의 function 은 FD 는 외부호출 불가능하고 FE 만 가능하다 2) 선언함수는 페이지 로딩이 완료가 되면 Execution Context 의 variable object 에 프로퍼티로 잡히나, 표현함수는 EC 의 VO 에 잡히지 않는다. 이런 사유로 표현함수는 선언이 되고 난 후 호출이 되어야 한다 (HOISTING) document.write(typeof xyz + "<br>"); // function function xyz(){ document.write("XYZ-1" + "<br>"); } ; function xyz(){ // 동일한 이름을 갖는 선언함수가 유효한지 확인유효함 document.write("XYZ-2" + "<br>"); } ; xyz() ; // XYZ-2, to see replace the function document.write(typeof xyk + "<br>"); // undefined (HOISTING) var xyk = function(){} ;
  • 42. 41 함수  함수 생성방법 : 세 가지로 분류된다 3) 자기호출함수 (Self Invoking) ; 표현함수 류 이면서, 즉시실행함수 라고도 한다 . (function () { } ) () ; // 함수는 누가 호출하는 것이 아니고, 자동으로 invoke 된다 . 일반객체 내에서는 구성이 불가능 하나, 함수객체 내에서는 구성이 가능하다 . 주로 수시로 사용되지 않고 1회성 으로 만 사용되는 초기화가 필요한 부분의 기능을 담당한다 . 특정객체를 argument 로 pass down 시킬 수 있다 . 내부 variable 및 function 은 마치 window 에 속하는 것처럼 전역화 (Global) 되어 진다 (function myFunc1() { kka = 100 ; // 전역 (If var then Local) alert("SI1") ; function test1(){ // 내부함수 alert("test1") ; } test2 = function(){ // 전역 (If var then Local) alert("test2") ; } test1() ; })() ; alert(kka) ; // Success //test1() ; // Error test2() ; // Success var f={ abc: 10 , }; (function myFunc2($){ alert (f.abc) ; })(f) ; // Pass down as $
  • 43. 42 함수  자기호출함수 를 이용하여 new 없이 wrapper 구현 var myObj={} ; myObj.myFunc = (function () { // 자기호출-1 alert("A") ; var WACFile = (function() { // 자기호출-2 alert("B") ; function WACFile(){ this.method1a = function () { alert("m1a") ; } ; } WACFile.prototype.method1b = function () { alert("m1b") ; return new FileStream ; }; return WACFile ; // To make CLOSURE })() ; function FileStream(){ // 내부함수객체 this.method2 = function () { alert("m2") ; } ; } function dfhandle(){ // 내부함수 return new WACFile ; } dfhandle1 = function(){ // 전역함수 return dfhandle() ; } })() ; var h1 = dfhandle1() ; var h2 = h1.method1b() ; h2.method2() ; < Wrapper> 구현 패턴정리 1. 표준적인 함수객체를 사용 : new 2. 일반객체를 싱글톤 으로 사용 : new 없이 3. 자기호출함수 의 전역함수를 이용 : new 없이
  • 44. 43 함수  함수생성 시 기본 상속관계 . 함수 가 생성되면 아래와 같이 내부객체인 prototype 객체 (일반객체,{}) 가 자동으로 만들어지며, 연관관계는 아래와 같다  내장객체인 Function 객체는 아래와 같은 세부 property 와 메소드를 지닌다 function f(){} properties method __proto__ prototype Function.prototype constructor __proto__ < Properties> . arguments . agrity . caller . length . name . prototype <Prototype Methods> . prototype.apply() . prototype.bind() . prototype.call() . prototype. isGenerator() . prototype. toSource() . prototype. toString() < Prototype Properties> . function f(){} ; document.write(f.constructor + "<br>"); // Function() document.write(f.constructor.prototype + "<br>"); // prototype() document.write(f.prototype + "<br>"); // Object document.write(f.prototype.__proto__+ "<br>"); // undefined document.write(f.prototype.constructor + "<br>"); // f() document.write(typeof f.constructor + "<br>"); // function document.write(typeof f.prototype + "<br>"); // object f.prototype constructor __proto__ Function 내장객체 properties prototype Object.prototype
  • 45. 44 함수  JS 함수의 사용적 특징 1) 반환 형이나 매개변수의 개수 와 형이 정의되지 않는다 (Type check 가 느슨하다 라는 특징) . 매개변수에는 value 혹은 reference (object or function) 가 가능하다 . 반환 (return) 은 없어도 가능하고, 없다면 “undefined” 가 return 되며, 어느 종류의 data type 포함하여 함수 나 객체도 반환형에 사용 될 수 있다 : return function / return { var,function,,} . 함수가 매개변수로 사용되는 대표적인 예는 callback 함수를 등록하는 것이다 (addEveentListener, setTimeout) . CLOSURE 라는 특성은 함수가 반환되어 사용되거나, 매개변수로 함수가 사용되는 경우 와 연관되어 지니는 Java Script 에서 중요한 개념이다 (추가 설명) 2) 함수 내에 자손함수 (inner or nested function ) 을 포함 할 수 있다 . 전역공간 의 최소화 및 내부함수를 외부에 노출시키지 않으려는 목적으로 사용된다 (마치 C언어의 static 함수처럼) . 자손함수 는 return 되어 외부에서 사용이 가능하다 3) 재귀함수 (함수 내에서 자신을 호출 하는 것) 가 가능하다 4) 호출 (Invoke) 되지 않고 실행될 수 있다 : 즉시실행함수 5) 자기 자신을 덮어쓰기를 할 수 있다 function myFunc1() { var abc = 100 ; var abd = "Kwon" ; var abe = function() {alert("abe")} ; //자손함수 return{ // 객체로 return 하는 예제. ab: abc, ac: abd, ad: abe } }; var ret = myFunc1() ; alert (ret.ab + ret.ac) ; ret.ad() ;
  • 46. 45 함수  함수 의 용도적 분류 : 1) 크게 두 가지로 분류 할 수 있다 (1) 생성자함수 : 원형객체로서 사용목적 (2) 일반함수 : 단지 특정 statement 만을 지닌다 *주1. 생성자함수 는 대문자로 시작하며, 일반함수는 소문자로 시작한다 2) 함수 내부구성 Property 는 내부 에서만 사용되며, 바깥에서 동적으로 추가도 가능하다 : Closure –memoization 에서 활용 function myFunction1 (a){ this.a = a, this.method1 = function () {} ; } myFunction1.prototype.method3 = function () {} ; document.write(typeof myFunction1 + "<br>"); // function var myObj1 = new myFunction1 ; myObj1.method3() ; function kkb (a,b){ // 선언식함수 (FD) return a*b ; } var kkc = function (a,b){ // 표현식함수 (FE) return a*b ; } Kkb(1,2) ; document.write(typeof kkb + "<br>"); // function function myFunc() { var a=10 ; // local b=20 ; // local c=function(){document.write(+a,+b)} ; // 내부함수 c() ; } myFunc.d = 30 ; // 추가 myFunc.e = function(){document.write(“aa”)} ; // 추가 myFunc[0]=function() ; // 추가 myFunc[“f”]=function() ; // 추가 == myFunc.f=function(){} myFunc() ; document.write(myFunc.b) ; // undefined document.write(myFunc.d) ; // 30 myFunc.e() ; // aa myFunc[0]() ; myFunc.kk() ;
  • 47. 46 함수  함수 의 용도적 분류 3) 생성자함수 는 단독으로 사용을 하지 않으며, Instance 객체를 위한 원형객체 이다 생성자함수 를 세부적으로 구성하는 구성요소는 아래와 같으며, prototype 은 하부 객체임을 알수있다 function myFunction1 (a){ this.a = a ; // Instance 대상변수 (멤버 변수)  Constructor var kka = 10 ; // 내부변수 this.method1 = function () {} ; // Instance 대상 method (멤버 메소드)  Constructor method2 = function () {} ; // 내부 메서드, 표현식 function kka() {} // 내부 메서드, 선언식 } myFunction1.staticMethod = function() ; // STATIC 메서드 추가 // prototype 정의 myFunction1.prototype.value = true ; myFunction1.prototype.SUCCESS= 1 ; // Constant myFunction1.prototype.method3= function () {} ; // 상속(공유) 을 위한 prototype document.write(typeof myFunction1.prototype + "<br>"); // object myFunction1.staticMethod() ; // Can access here //myFunction1.method1() ; // ERROR – Instance 객체 에서만 생성되는 method //myFunction1.method2() ; // ERROR – 내부함수 접근불가 //myFunction1.method3() ; // ERROR – Instance 객체 에서만 공유되는 method
  • 48. 47 함수  함수의 용도적 분류 4) prototype 확대 (1) prototype 은 일반객체 로서 객체의 성격 과 동일하게 객체 구성 분 (property) 을 동적으로 추가 할 수 있다 (2) 동적으로 추가되는 것도 Instance 생성객체에서 사용가능 하다 function K(){ // 함수객체 } K.prototype ={ // prototype 객체 property 사전구성 a:3, b:function(){document.write("aa")} } var a = new K() ; // protype 객체 property 추가 K.prototype.e=function(){document.write("cc")} ; K.prototype.f=20 ; a.b() ; a.e() ;
  • 49. 48 객체 와 함수  일반객체 와 함수객체 의 차이점 정리 . 둘 다 객체적 성격을 지녀서 내부에 property, 일반객체 및 함수객체를 포함 한 다. . typeof 로 확인시 “object” 와 “function” 으로 구분이 된다 . 일반객체는 원형객체로서 사용은 되지 못하고, 싱글톤 객체로만 사용된다 . 함수객체는 원형객체로 사용되며, 객체의 생성부분을 위한 constructor 와 상속을 위한 prototype 을 지닌다. 이를 위하여 prototype 이라는 property 명으로 내부객체 (일반객체) 를 지닌다.
  • 50. 49 함수 – 객체화 및 상속  생성자함수 를 원형객체로 하여 아래와 같은 기본적인 객체화 및 상속을 적용한다 . 객체화 로 생성되는 myObj1 이 type 이 함수가 아니고 일반객체 (object) 임을 기억해라. . “instanceof” 라는 key word 를 사용하여 원형객체 임을 알 수 있다 var myObj1 = {} ; document.write(myObj1.constructor + "<br>"); // function Object() var myObj1 = new myFunction1 ; document.write(typeof myObj1 + "<br>"); // object if(myObj1 instanceof myFunction1) document.write("Inherited"+ "<br>"); // Inherited myObj1.method1() ; // Instance method myObj1.method3() ; // 상속(공유) document.write(myObj1.__proto__ + "<br>"); // undefined document.write(myObj1.constructor + "<br>"); // function myFunction1() Object. prototype myObj1 myFunction1. prototype myObj1
  • 51. 50 함수 – 객체화 및 상속  생성자함수 의 원형객체 사용 생성자함수 를 원형으로 하여 새로운 Instance 객체 생성을 하거나, 상속 (공유) 을 하는것을 클래스방식의 상속패턴이라 하며, 크게는 5가지 방법이 있다 방법1. 기본적인 방법 . constructor (this 로 지니는 property 및 method) 는 Instance 객체에서 new 의 대상이 된다 (복사되어 새로운 것을 지닌다) . prototype 은 상속의 대상이 된다 (공유를 한다) constructor prototype Instance객체 생성자함수 property method 공유 Instance var myObj1 = new myFunction1 ; myObj1.method1() ; myObj1.method2() ; // ERROR myObj1.method3() ; 방법 요약 Constructor 멤버 (this.x ) Instance Prototype 상속 방법1 기본 O O 방법2 생성자 빌려쓰기-1 O X 방법3 생성자 빌려쓰기-2 O O 방법4 Prototype 공유 X O 방법5 임시 생성자 X O
  • 52. 51 함수 – 객체화 및 상속  생성자함수 의 원형객체 사용 방법2. 생성자 빌려쓰기 를 이용하는 방법 . 내장객체 (Function.prototype) 의 apply 혹은 call 메소드 를 이용하는 방법 이다 . Constructor (this 로 지니는 Property 및 Method) 는 Instance 객체에서 new 의 대상이 되지만, prototype 은 상속 (공유) 하지 않는다 . 생성자 빌려쓰기 를 이용하여 다중상속 구현이 가능하다 constructor prototype Instance객체 생성자함수 property method Instance function myFunction2(name) { myFunction1.apply (this,arguments) ; } var k = new myFunction2 ("denver") ; document.write(k.a + "<br>"); // denver k.method1() ; //k.method3() ; // ERROR Function constFunc1() { this.kka = 3 ; this.kkb = function(){} ; } Function constFunc2() { this.kkc = 4; this.kkd = function(){} ; } function InstanceOnly() { constFunc1.apply (this) ; constFunc2.apply (this) ; } var multiInherit = new InstanceOnly() ;
  • 53. 52 함수 – 객체화 및 상속  생성자함수 의 원형객체 사용 . 기타 상속패턴 방법3. 생성자 빌려주기를 사용 ; Instance 생성과 prototype 을 상속 받는다 방법4. Prototype 을 공유한다 ; Prototype 만 상속한다 방법5. 임시생성자 를 이용한다 ; Prototype 만 상속한다 // 방법3 function myFunction2(name) { myFunction1.apply (this,arguments) ; } myFunction2.prototype = new myFunction1() ; var k = new myFunction2 ("denver") ; document.write(k.a + "<br>"); // denver k.method1() ; // Okay k.method3() ; // Okay // 방법5 function myFunction2(){} ; function Inherit5(Child, Parent) { var F = function() {} ; F.prototype = Parent.prototype ; Child.prototype = new F() ; } var k = new myFunction2() ; Inherit5(myFunction2,myFunction1) ; //k.method1() ; // ERROR k.method3() ; //상속(공유) --> 되어야 하는데 ERROR 난다 (***) // 방법4 function myFunction2(){} ; myFunction2.prototype = myFunction1.prototype ; var k = new myFunction2() ; //k.method1() ; // ERROR k.method3() ; // 상속(공유) document.write(myFunction1.prototype + "<br>"); // [object Object] document.write(myFunction2.prototype + "<br>"); // [object Object]
  • 54. 53 함수 - CLOSURE  CLOSURE 란 . 함수 의 사용적 특징 중에 자손함수를 지닐 수 있고, return 되어 사용될 수 있고, 또한 인자로도 사용가능 한 특징이 있다 . 또한 Execution Context Stack 의 특징에 의하여 EC 는 activated 가 종료되면 내부 변수들은 모두 free 가 되어진다 (별도의 Garbage collector 가 있다 ?) . 해서, 정리하면 아래와 같은 특징을 CLOSURE 라 한다 1) return 함수에 사용되는 variable 이 free 되어진 상태이나, return 함수에 사용된다 2) return 되는 함수 혹은 매개변수로 사용되는 함수의 scope chain 을 기억하여 해당 variable 을 찾을때 활용하는 것을 지칭한다 3) 이를, Static (lexical) scope 라 칭하며 (in contrast with Dynamic scope), ECMA script 에서는 static scope 방법이 사용된다  예 (Example) < Case 1. return function 인 경우 > var Y = 10 ; function kka() { var Y = 200 ; return function kkb() { document.write (Y) ; // 200 not 10 } } var retFunc = kka() ; retFunc() ; // Invoke kkb() < Case 2. function 이 매개변수인 경우> var X = 10 function kkc(){ document.write (X) ; // 10 not 100 } (function kkd(funcArg) { var X=100 ; funcArg() ; } )(kkc) ; // pass down as “funcArg” Global EC kka EC kkb EC Global EC kkd EC kkc EC
  • 55. 54 함수 - CLOSURE  CLOSURE 활용 패턴 1) 함수내의 Local Variable 을 마치 static 변수처럼 사용하게 한다 . 즉, closure 가 발생되면, scope chain 에 기억된 함수들의 Variable Object 들은 메모리에서 상주한다 . 이를 이용하여 Local Variable 을 마치 static 변수처럼 사용할 수 있다 . 예제를 통하여, myFunction7() 이 지니는 xyz 이 static 변수처럼 사용 됨을 알 수 있다 // 일반함수 로 사용시 unction myFunction6(k) { var xyz ; if (k==true) xyz = 1 ; // 초기화 else xyz++ ; // lead to NaN document.write(xyz + "<br>"); } myFunction6(true) ; // 1 myFunction6(false) ; // NaN // CLOSURE 로 사용시 function myFunction7() { var xyz=1 ; return function() { xyz++ ; // xyz is cached document.write(xyz + "<br>"); } } var retFunc = myFunction7() ; // document.write(+xyz) ; // can't access retFunc() ; // 2 retFunc() ; // 3
  • 56. 55 함수 - CLOSURE  CLOSURE 활용 Pattern 2) 커링 (Curring) . 원본함수 와 매개변수 일부를 물려받는 새로운 함수를 생성 하는 것을 의미한다 커리할 원래 함수와 인수를 유지하는 클로저를 만드는 방식으로 동작한다. . 어떤 함수를 호출할 때 대부분의 매개변수가 항상 비슷하다면, 커링 의 적합 한 사용대상이라고 볼 수 있다 . 매개변수 일부를 저장하여 새로움 함수를 동적으로 생생하면 이 함수는 반복되는 매개변수를 내부적으로 저장하여, 매번 인자를 전달하지 않아도 원본 함수가 기대하는 전체목록을 미리 채워놓을 것이다. . Functional programming 에서 공통적인 사용 모델이다 //1. 기준함수를 설정한다. function seq( start, end ) { var i; for( i = start; i < end; ++i ){ document.writeln( i ); } } //2. Closure 함수에서 원함수를 내부함수의 최종 결과를 생성하도록 만든다. function fixSeqStart( start ) { return function( end ) { return seq( start, end ); // start should be closure } ; } //3. 함수를 부분별로 실행한다. var seq10 = fixSeqStart( 10 ); // Print out numbers from 10 to 20 seq10( 21 );
  • 57. 56 함수 - CLOSURE  CLOSURE 활용 Pattern 3) 메모이제이션 . 특정한 함수의 결과가 매개변수의 조건에 따라 고정적인 경우, 해당 값을 cached 시켜놓고, 두번째 부터 는 함수를 호출하지 않고 Cached 값을 return 하여 준다 – 성능향상을 위함. . Cached 를 위하여 원래함수에 Buffer 를 만든다  해당함수의 VO 가 소멸되지않고 cached 되는 원리를 이용한다 . Fibonachi (피보나치) 수열 을 예로 든다 (최초의 두항이 1,2 이고 그 뒤는 앞서는 두항의 합이 그 다음 항의 수가되는 수열) function memo(f) // //메모이제이션 함수 정의 { return function (x) { // closure 함수 f.memo = f.memo || {}; // 원래함수 f에 Closure 생성한다 return (x in f.memo) ? f.memo[x] : f.memo[x] = f(x); }; } //원래 함수 (피보나치 수열을 구하는 함수) function fib(x) { if(x < 2) return 1; else return fib(x-1) + fib(x-2); } // fib.memo={} // static buffer //함수 실행 var memoFib = memo(fib); document.write(memoFib(1) + "<br>"); // 1 document.write(memoFib(2) + "<br>"); // 2 document.write(memoFib(3) + "<br>"); // 3 = 1+2 document.write(memoFib(4) + "<br>"); // 5 = 2+3 document.write(memoFib(5) + "<br>"); // 8 = 3+5 document.write(memoFib(6) + "<br>"); // 13 = 5+8 document.write(memoFib(5) + "<br>"); // 8 , CACHED document.write(memoFib(6) + "<br>"); // 13 , CACHED CLOSURE 함수 Cached 원래함수 실행 Cached Buffer Closure 함수에 인자로 원래 함수 를 준다 Cached Buffer Buffer 생성 No Return from Cached Buffer Yes
  • 58. 57 Execution Context Stack  JS 가 Load 되어 실행이 진행중인 (activated, program runtime) code 영역을 ECS 라 한다 . 실행 context : 코드실행의 작은 조각을 capsule 화 한 property 를 가지고 있는 어떤 객체들의 집합 . 특정 Java Script 는 일반적으로 다음과 같은 요소들로 구성될것이며, 전역공간을  ECMA script 에서 규정한 code (Execution Context) 는 세가지 로 구성된다 : global , function and eval . global context 는 단 하나로 존재하며, global EC 를 실행하는 객체는 내장객체인 window 이다 . function 과 eval 에 대한 EC 는 다수 개 가 있을 것이다 . 함수가 호출 (Activate) 되어 지면, function ECS 로 진입하고 (Activated), return 되면 해당 ECS 는 소멸되고 caller 의 ECS 로 간다 . 내부함수는 outer function 과는 독립적인 새로운 function ECS 를 지닌다. . eval 과 setTimeout 은 그 특성 상 function 이 아닌 별도의 ECS 를 지닌다. // main.js . variable ; 전역공간 . 일반객체 ; 전역공간 . 선언함수 . 표현함수 . 즉시실행함수 . Expression & Statement Global EC FunctionA EC FunctionB EC return return Activate ActivateBegin
  • 59. 58 Execution Context Stack  Execution Context 세부 . 각 EC 는 Context 의 상태 (state) 를 위한 properties 들을 아래와 같이 지니고 있다. . VO 는 해당 EC 과 연관된 scope of data 로 정의하며 variables 와 argument 및 선언함수를 store 하고 있다. *주1. 표현함수 및 자기호출함수 는 VO 에 포함되지 않는다. 이런 이유로 표현함수 에 대한 호출위치는 항상 표현함수 뒤에서 해야하며 이를 HOISTING 이라 한다. *주2. arguments 는 함수 EC 에서만 존재한다 . thisValue : EC stack 을 실행호출한 어느 context 인 객체 를 의미한다 (EC 에 진입되면 determine 되어지고 변경될 수 없다) . function EC 가 activated 되어지면, 특별한 object 인 Activation Object (AO) 가 만들 어지며, 이 AO 는 VO 역할을 한다. Variable Object (VO) [ vars, 선언함수, arguments,, ] Scope Chain [ VO + All Parent Scope ] thisValue Context Object XXXX EC function foo(x,y) { var z = 30 ; function bar() {} // FD (function baz() {}); // FE } foo (10,20) // invoke (activate) < Activation Object of foo> x 10 y 20 arguments {0:10,1:20,..} z 30 bar <function>
  • 60. 59 Execution Context Stack  Scope Chain . 아래와 같은 myFunction1 함수를 Invoke 한다고 하면, 우측 그림과 같은 실행순서, EC 와 Scope chain 이 형성된다 Scope Chain 이란 자신의 함수의 AO 영역에서 발견되지 않는 reference 에 대하여 caller 함수의 AO 영역을 찾는 scope 이다. var aaa =10 ; var myObj = {} ; myObj.myFunction4 = function() // For the Scope Chain { var bbb = "BBB" ; document.write(aaa + "<br>"); // AAA function kka(){ // FD var ccc = "CCC" ; document.write(aaa + "<br>"); // AAA document.write(bbb + "<br>"); // BBB //document.write(ddd + "<br>"); // ERROR } var kkb = function (){ // FE var ddd = "DDD" ; (function kkc(){ // 즉시 실행함수 var eee = "EEE" ; document.write(bbb + "<br>"); // BBB document.write(ddd + "<br>"); // DDD }) () ; }; (function kkd(){ // 즉시 실행함수 var fff = "FFF" ; document.write(bbb + "<br>"); // BBB })() ; kka() ; kkb() ; //document.write(ccc + "<br>"); // ERROR }; myObj.myFunction4() ; Global EC myFunction4 EC kkd EC kkb EC kkc EC VO aaa myObj kka EC AO bbb kka AO ddd AO fff *주1. kkc 함수의 Scope Chain 은 kkc  kkb  myFunction1  Global 이다.
  • 61. 60 Execution Context Stack  this 의 정의 . Keyword 로서 특정 객체를 의미한다 (지칭 하거나 객체의 전체 context 를 나타낸다) (1) 일반객체 내에서는 code 의 소유주 객체를 나타낸다 (예. window.kkb() ) (2) 생성자 함수를 이용하여 만들어진 Instance 객체 의 메소드 (instance or prototype) 내의 this 는 해당객체를 의미한다. (3) String 이나 Array 같은 내장객체는 객체자체가 context 전체와 동일하게 사용된다 . 생성자 함수 내에서의 this 는 값을 가지지 않고, 신규객체의 Instance 대상 임을 의미한다 < Code 의 소유주 객체를 의미> document.write(typeof this + "<br>"); // object var a = "window" ; document.write(this.a + "<br>"); // window var myObj1 = { a:"myObj1", method1 : function() { document.write(this.a + "<br>"); // myObj1 kkb(); // window } } ; var myObj2 = { a:"myObj2", method1 : function() { document.write(this.a + "<br>"); // myObj2 kkb(); // window } } ; function kkb (){ document.write(this.a + "<br>"); // "window" } this.kkc = function(){ // same with window.kkc document.write(this.a + "<br>"); // "window" } myObj1.method1() ; // “myObj1” “window” myObj2.method1() ; // “myObj2” “window” this.kkb() ; // "window" window.kkb() ; // "window" < 객체의 전체 context 를 의미> var str1 = "korea" ; var str2 = "japan" ; String.prototype.test = function(){ document.write(this + "<br>"); } str1.test() ; // will print "korea" str2.test() ; // will print "japan var ara1 = ["kka","kkb"]; var ara2 = ["kkc","kkd"]; Array.prototype.test = function(){ document.write(this + "<br>"); } ara1.test() ; // will print "kka,kkb" ara2.test() ; // will print "kkc,kkd” var obj1= {a:1,b:2} ; var obj2= {c:1,d:2} ; Object.prototype.test = function(){ document.write(this + "<br>"); } obj1.test() ; // will print "[object Object]" obj2.test() ; // will print "[object Object]" var fnc1= function(){a=1} ; var fnc2= function(){b=1} ; Function.prototype.test = function(){ document.write(this + "<br>"); } fnc1.test() ; // will print "function(){a=1}" <생성자함수의 Instance 객체를 의미) function myFunction1 (){ // 생성자함수 this.a ; this.method1 = function () { document.write(this.a + "<br>"); } ; } myFunction1.prototype.method4 = function(){ document.write(this.a + "<br>"); } ; var myObj1 = new myFunction1 ; var myObj2 = new myFunction1 ; myObj1.a = 10 ; myObj2.a = 20 ; myObj1.method1() ; // 10 myObj2.method1() ; // 20 myObj1.method4() ; // 10 myObj2.method4() ; // 20
  • 62. 61 Execution Context Stack  this 의 정의 . Code 의 소유주 객체를 의미한다는 것은 아래와 같이 추가적으로 define 된다 1) window 하부의 일반함수나 global variable 의 this 는 window 이다 2) 일반객체 내부의 this 는 해당객체이다 < Code 의 소유주 객체를 의미> var myObj1 = { a:"myObj1", method1 : function(){ document.write(this.a + "<br>"); // myObj1 } } ; var myObj2 = { a:"myObj2", method1 : function(){ document.write(this.a + "<br>"); // myObj2 } } ; var a = "window" ; document.write(this.a + "<br>"); // window function kkb(){ document.write(this.a + "<br>"); } kkb() ; // window kkb.apply(myObj1) ; // myObj1  임의기능을 사용하여 객체의 주인을 변경한다 kkb.call(myObj2) ; // myObj2  임의기능을 사용하여 객체의 주인을 변경한다 myObj1.method1() ; // myObj1 myObj2.method1() ; // myObj2
  • 63. 62 Execution Context Stack  This 위임기능 . Function.prototype 이 지닌 method (apply, call) 를 이용 : 위임기능 이라 하며, this 를 임의적으로 명시하기 위함이다 . 즉, function execution context stack 에서 this 를 임의적으로 변경(명시) 한다 window 객체 Function. prototype Kkb() kkb.apply(myObj1,args) This = window This = myObj1 <this 의 위임, window  myObj1 > var myObj1={a:"myObj1"} ; var myObj2={a:”myObj2”} ; var a = "window" ; document.write(this.a + "<br>"); // window function kkb(){ document.write(this.a + "<br>"); } kkb() ; // window kkb.apply(myObj1) ; // myObj1 kkb.call(myObj2) ; // myObj2 kkb() ; // window < apply / call 의 차이> function sum(){ var result=0, n; for(n=0;n<arguments.length;n++){ result+=arguments[n]; } this.result=result; } var sumA={result:0}; var sumB={}; // apply -> arguments 로 호출 sum.apply(sumA, [1,2,3,4,5,6,7,8,9]); document.write(sumA.result + "<br>"); // 45 // call -> parameter를 개별로 sum.call(sumB, 1,2,3,4,5,6,7,8); document.write(sumB.result + "<br>"); // 36
  • 64. 63 디자인 Pattern  패턴이란 : 모범적인 관행, 쓰임새에 맞게 추상화 된 원리, 어떰 범주의 문제를 해결하는 template  모듈화 (namespace) . 전역객체를 최소화 하고, 객체를 기능별, 목적 별로 모듈화 하기 위하여 tree 화 시킨다  싱글톤 패턴 . 원 의미는 특정 클래스의 Instance 를 오직 하나만 사용하는 패턴을 의미한다 . 적용방법 1) 일반객체의 성격상 그대로 사용하면 싱글톤 이 된다 (var myObj2 = new myObj1 이 불가능한 특징을 이용한다) 2) 생성자함수 를 변형 : Constructor 행위가 한번 만 이루어지게 조작한다 MYAPP Module1 Module2 Module3 Interface1 Interface2 Interface3 MYAPP = {} ; MYAPP .Module3= {} ; MYAPP .Module3.Interface3 = function() {} ; function myFunction1(a){ if (typeof myFunction.instance == “object”) return myFunction.instance ; this.a = a ; myFunction.instance = this ; // static property }
  • 65. 64 디자인 Pattern  Factory 패턴 . 객체생성 대리인 역할을 하는 것으로서, new 를 사용하지 않고 객체가 지닌 Static 메소드에 객체생성을 요청하는 것이다. . 원래 Java 에서는 타입을 모르고서도 객체생성을 요청하는 패턴을 의미한다 . 아래의 예제에서, 동일한 모델이면 동일한 객체를 사용토록 응용하는 Factory 패턴을 사용하였다 function Car(model,color){ this.model = model ; this.color = color ; } Car.models=[] ; Car.instances=[] ; Car.factory = function(model,color){// STATIC 메소드 var factory ; for(var i=0 ; i < Car.models.length ; i++){ if(Car.models[i] == model){ document.write("Already Instanced"+ "<br>"); return Car.instances[i] ; } }; document.write("New Instances=" + Car.models.length + "<br>"); Car.models[Car.models.length] = model ; factory = new Car(model,color) ; Car.instances[Car.models.length] = factory ; return factory ; }; var a = Car.factory("sonata","black") ; var b = Car.factory("sonata","black") ; var c = Car.factory("k7","black") ; if(a==b) // 실제이리 되지않고, 개념적이다 document.write("Same Instance"+ "<br>");
  • 66. 65 디자인 Pattern  퍼사드 (Facade) 패턴 . 원래의 의미는 App 의 편리성을 위하여 여러 객체 들의 method 를 하나의 통합된 method 로 구성 하는 것을 의미한다 . New 가 가능하지 않는 object (주로 plug-in) 에 대하여 interface 를 두어서 App 에서 접근하게 하는 방법이며, 이런 Interface 를 wrapper 라 하며, 생성자함수 객체로 구성한다 Wrapper.js Module = Module || {} ; Module.interface = function(){} // Constructor Module.interface.prototype.method = function(){} // API Module.interface.prototype.onEvent = function(){} // Event Plug-In Object Main.js var intA = new Module.interface() // 객체생성 intA.onEvent = intOnEvent ; // Event function intOnEvent() {} . Using Object or Embedded Tag . Private API dependent upon Browser module.interfcae = function() { var divNode = document.createElement("div"); divNode.id = ‘XXXXX_plugin'; divNode.innerHTML +="<OBJECT id='pluginObjectXXX' border=0 classid='clsid:SAMSUNG-INFOLINK-TV‘ style='opacity:0.0;background-color:#000000;width:0px;height:0px;'></OBJECT>"; document.body.appendChild(divNode); pluginObjXXX = document.getElementById('pluginObjectXXX'); pluginObjXXX.Open (‘EMP-MODULE-NAME', '1.000', ' EMP-MODULE-NAME ')); } module.interfcae.prototype.method = function() { pluginObjXXX.Execute ('App1', '1.000', 'App1')); } pluginObjXXX.OnEvent (event,type) = function (){ module.interfcae.prototype.onXXEvent() ; }
  • 67. 66 이벤트  이벤트 란 : 특정 Object 에게 사용자 (혹은 서버 나 장치) 가 메시지의 도달이나 요청사항을 통지 하는것.  이벤트 등록방법 - 4가지 방법 1) Document 내에 element 선언 시 해당되는 이벤트에 function 을 연결 시킨다 2) JS 내에서 해당되는 객체의 이벤트에 function 을 연결 시킨다 : * 이때 onclick 에 대한 property 가 define 되어진다, event 전달은 안된다 3) JS 내에서 Window.event 객체에게 listener 를 등록한다 4) Link element 가 지니는 “href” 에 java script 함수와 연결시킨다 ; button 없이 JS function 을 호출하고자 할때 사용 <script> function myEvent1(event) { var try1 = document.getElementById("try1") ; var try4 = document.getElementById("try4") ; document.write(typeof try1.onclick + "<br>"); // function document.write(typeof try1.name + "<br>"); // unknown document.write(typeof try1.any + "<br>"); // unknown document.write(typeof try4.onclick + "<br>"); // unknown } function myEvent2() { document.write("myEvent2" + "<br>"); } function myEvent3(event) { document.write("myEvent3" + "<br>"); } </script> <body> <p> My Event Test by Hungrok Kwon </p> <button id="try1" onclick="myEvent1(event)">Try1 </button> // 방법1 <button id="try2" >Try2 </button> <button id="try3" >Try3 </button> <button id="try4" >Try4 </button> <a href=“Javascript: myEvent1(event)” > Test </a> // 방법4 </body> <script> function window.onload() // 페이지 laod 후 최초로 불린다 { var try2 = document.getElementById("try2") ; var try3 = document.getElementById("try3") ; try2.onclick = myEvent2 ; // 방법2 try2.onclick = myEvent2(event) ; // 방법2 but ERROR try2.onAny = myEvent2 ; // No ERROR try3.addEventListener(onclick,myEvent3(event)) ; // 방법3 - ERROR at IE } <script>
  • 68. 67 이벤트  Event Propagation . 특정 이벤트 (type) 가 발생하면, 동일한 event 에 대하여 상,하위 노드 간 에 순차적으로 이벤트가 발생한다 - 상위노드  하위노드 로 이벤트 진행순서를 capturing 이라 함, - 하위노드  상위노드 로 이벤트 진행순서를 bubbling 이라 함, IE 스타일 . 하기 예와 같이 button-1 에서 onlclick 이 발생하면, button-1  div-2  div-1 순서로 event 가 발생한다 (동일한 노드 계층간에는 이벤트가 발생하지 않는다) . 노드 간 event propagation 을 중지 하기위하여는 Event Object 가 제공하는 stopPropagation() 메소드를 이용할 수 있다 div-1 div-2 button-1 button-2 select <script> function myEvent1(){ alert (“Event1”) ; } ; function myEvent2(){ alert (“Event2”) ; } ; function myEvent3(){ alert (“Event3”) ; } ; function myEvent4(Event){ alert (“Event4”) ; event.stopPropagation() ; } ; function myEvent5(){ alert (“Event5”) ; } ; <body> <p> Event Propagation test by Hungrok Kwon </p> <div id="div1" onclick="myEvent1()"> <div id="div2" onclick="myEvent2()"> <button id="try1" onclick="myEvent3()">Try1 </button> <button id="try2" onclick="myEvent4()">Try2 </button> <select id="sel1" onclick="myEvent5()"> </select> </div> </div> </body>
  • 69. 68 이벤트  Event 객체의 전달 . Event 가 발생하면 해당 Java Script 함수가 호출되면서 event 객체도 argument 로 전달된다 * event 등록방법 중 방법2는 event 객체를 argument 로 전달 할 수 없다. < Event 객체 Properties > . bubbles ; Returns whether or not an event is a bubbling event . cancelable ; Returns whether or not an event can have its default action prevented . currentTarget ; Returns the element whose event listeners triggered the event . eventPhase ; Returns which phase of the event flow is currently being evaluated . target ; Returns the element that triggered the event . timeStamp ; Returns the time (in milliseconds relative to the epoch) at which the event was created 2 . type ; Returns the name of the event function(){}Event (onclick) Event 객체
  • 70. 69 JS Library  Library . App. 개발의 편의성을 위하여 일종의 대리적인 Macro API 를 제공하는 Java Script 이다 . JQUERY, YUI, PROTOTYPE 등이 많이 사용되는 Library 들이다.  JQUERY . 다양한 선택자 를 기반으로 객체에 대한 Effect 효과, Animation 효과, AJAX 및 기타 기능을 가져 가는데 편리하다 . 자세한 내용은 여기서는 다루지 않고, 개념적인 것만 기술한다 CSS3 JQUERY Lib Style EffectJava Script Event JQUERY Event $(선택자).method() DOM Objects 1.Effect 를 위한 메소드 : Hide, Show, Fade, Slide, Animate, Chaining 2. HTML 관련 메소드 (1) DOM Manipulating: text, html, val, attr, append, prepend, before, clone, after, remove, empty (2) CSS Manipulating: add/remove/toggleClass, css (3) Dimension : width, height, innerWidth, innerHeight, outerWidth, outerHeight (4) 기타 : 3. Traversing 4. AJAX