<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>세계의끝과 플래시 원더랜드 &#187; 고수들은 가르쳐주지 않는 AS3.0 입문</title>
	<atom:link href="http://ufx.kr/blog/category/flashpaltform/beginner-as3/feed" rel="self" type="application/rss+xml" />
	<link>http://ufx.kr/blog</link>
	<description>Flash + ActionScript &#38; Design</description>
	<lastBuildDate>Fri, 27 Jan 2012 21:51:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>null 객체 에러 예방을 위한 액션스크립트 클래스의 초기화 순서 이해하기</title>
		<link>http://ufx.kr/blog/853</link>
		<comments>http://ufx.kr/blog/853#comments</comments>
		<pubDate>Mon, 11 Apr 2011 18:58:53 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[static]]></category>
		<category><![CDATA[객체]]></category>
		<category><![CDATA[디버깅]]></category>
		<category><![CDATA[생성자]]></category>
		<category><![CDATA[에러]]></category>
		<category><![CDATA[인스턴스]]></category>
		<category><![CDATA[초기화]]></category>
		<category><![CDATA[클래스]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=853</guid>
		<description><![CDATA[애플리케이션의 실행은 초기화(Initalize) 라는 과정을 가장 먼저 거치게 됩니다. 애플리케이션이 실행되기 전에 메모리에 띄워 놓을것은 띄워 놓고 이런저런 것들을 변수에 할당한 후에 실행을 준비하는 단계죠. 어떤 것들이 초기화에 해당하는지 이해하고 있고, 그 순서를 정확하게 이해하고 있다면 컴파일 단계에서 에러의 숫자를 획기적으로 줄일 수 있기 때문에 이 초기화 단계를 이해하고 있는 것은 매우 중요합니다. 특히 여러분이 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="align size-full wp-image-" alt="" /><img class="alignleft size-full wp-image-862" title="hp_application" src="http://ufx.kr/blog/wp-content/uploads/2011/04/hp_application.png" alt="" width="150" height="150" />애플리케이션의 실행은 초기화(Initalize) 라는 과정을 가장 먼저 거치게 됩니다. 애플리케이션이 실행되기 전에 메모리에 띄워 놓을것은 띄워 놓고 이런저런 것들을 변수에 할당한 후에 실행을 준비하는 단계죠.</p>
<p>어떤 것들이 초기화에 해당하는지 이해하고 있고, 그 순서를 정확하게 이해하고 있다면 컴파일 단계에서 에러의 숫자를 획기적으로 줄일 수  있기 때문에 이 초기화 단계를 이해하고 있는 것은 매우 중요합니다. 특히 여러분이 null 객체 에러를 자주 만난다면 반드시 이  포스트를 정독할 필요가 있습니다.</p>
<p>“그거라면 이미 다 알고 있는 내용이잖아!!” 라고 불평하시는 현업 개발자 여러분들에게는 보너스로, static 생성자함수(!?)를 소개합니다. 이런분들은 <a href="http://ufx.kr/blog/853#d2" target="_self">D-2.클래스 생성자</a> 부터 읽으셔도 되겠습니다.</p>
<p><span id="more-853"></span></p>
<h3>A. 클래스는 무엇으로 이루어져 있는가?</h3>
<p>객체지향에서 클래스를 역할 관점으로 본다면, 객체를 만들어 내는 ‘설계도’, 또는 ‘틀’ 이라고 할 수 있습니다. 한편 프로그래밍의  구조적인 관점에서 클래스가 어떤 내용물로 구성되어 있는지 들여다 봤을때는 속성(변수)과 메서드가 보이게 되죠.</p>
<h5>변수의 종류</h5>
<ul>
<li>인스턴스 변수(instance variable)</li>
<li>클래스 변수(class variable)</li>
<li>로컬 변수(local variable)</li>
</ul>
<h5>메서드의 종류</h5>
<ul>
<li>인스턴스 메서드(instance method)</li>
<li>클래스 메서드(class method)</li>
<li>로컬 메서드(local method)</li>
</ul>
<p>우리는 위와 같은 여러 종류의 요소를 클래스 멤버(class member)라고 부릅니다. 이 포스트에서는 후자의 관점으로 봤을때의 클래스와 멤버들에 대해 이야기를 하게 됩니다.</p>
<h3>B. 변수(variable)</h3>
<h4>B-1. 인스턴스 변수 (instance variable)</h4>
<p>우리가 보통 private var, public var 와 같은 키워드를 붙여 선언하는 변수는 인스턴스 변수에 해당합니다. 인스턴스  변수는 클래스를 이용해 객체(instance)를 생성한 경우에만 의미를 가지게 되므로 이런 명칭이 붙었습니다. 너무나 당연하죠?  우리가 Product 라는 이름의 클래스에 정의한 name 이라는 이름의 인스턴스 변수는 아래와 같이 정의되고&#8230;</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">name</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>; <span style="color: #009900;">// 인스턴스 변수 선언</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>호스트코드에서 아래와 같이 인스턴스 화를 거쳐 객체를 생성한 이후, 그러니까 new Product() 를 한 순간 이후부터 name 이라는 속성을 사용할 수 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span>Product
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> instance.<span style="color: #004993;">name</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 이 시점에서는 객체가 생성되지 않은 시점이므로 속성에도 접근불가</span>
instance = <span style="color: #0033ff; font-weight: bold;">new</span> Product<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 객체 생성</span>
instance.<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;시리즈1번&quot;</span>; <span style="color: #009900;">// 속성에 접근 가능</span></pre></td></tr></table></div>

<h4>B-2. 클래스 변수 (class variable)</h4>
<p>그런데 클래스 변수라는 것이 있습니다. 우리 액션스크립트 동네에서는 클래스 변수를 static 키워드로 만들기 때문에 static  변수 라고도 부르지만, 이 포스트에서는 인스턴스 변수와 구별되는 변수라는 의미로 클래스 변수라고 표기하겠습니다.</p>
<p>클래스 변수는 객체가 아닌 클래스 자체에 속하기 때문에 객체를 생성하지 않고도 사용할 수 있습니다. 위에서 만든 Product 클래스에 클래스 변수를 추가해 볼까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		static <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">type</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span> = <span style="color: #990000;">&quot;휴대전화&quot;</span>; <span style="color: #009900;">// 클래스 변수 선언하고 값을 대입</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">name</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>; <span style="color: #009900;">// 인스턴스 변수 선언</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>클래스 변수는 클래스가 import 되어 있고 클래스의 이름만 알고 있다면 아래와 같이 인스턴스를 생성하지 않아도 아무곳에서나 사용할 수 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> Product.<span style="color: #004993;">type</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력 : 휴대전화</span></pre></td></tr></table></div>

<h4>B-3. 로컬 변수 (local variable)</h4>
<p>또  한가지의 변수로는 로컬 변수(지역 변수)가 있습니다. 메서드 내부에서 사용하기 위해 선언한 변수를 일컫는 명칭이죠. 지역변수는  private, protected, public의 접근 제한자를 붙이지 못합니다. 접근 제한자들은 클래스 본문에 펼쳐 있는  멤버들만 사용할 수 있기 때문입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		static <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">type</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span> = <span style="color: #990000;">&quot;휴대전화&quot;</span>;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">name</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>;
		prublic <span style="color: #339966; font-weight: bold;">function</span> Product<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> temp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>; <span style="color: #009900;">// 로컬 변수 선언</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>로컬 변수는 객체 외부에서도 접근할 방법이 없음은 물론이거니와 클래스 내부에서도 메서드 외부에서 접근할 방법이 없습니다. 오로지 메서드 내부에서만 생성, 사용, 참조, 소멸 됩니다.</p>
<h3>C. 메서드(Method)</h3>
<h4>C-1. 인스턴스 메서드 (instance method)</h4>
<p>변수와 마찬가지로 private function, public function 등의 키워드로 정의되고 인스턴스화 되지 않으면 사용할 수 없습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		prublic <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span> <span style="color: #009900;">// 인스턴스 메서드</span>
			<span style="color: #009900;">// 인스턴스 메서드 바디</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>C-2. 클래스 메서드 (class method)</h4>
<p>변수와 마찬가지로 인스턴스 메서드에 static 키워드를 붙이면 클래스 메서드가 됩니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		static prublic <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span> <span style="color: #009900;">// 클래스 메서드</span>
			<span style="color: #009900;">// 클래스 메서드 바디</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>C-3. 로컬 메서드 (local method)</h4>
<p>변수와 마찬가지로 메서드 내부에서 어떤 로직을 처리하기 위해 만들어 놓은 메서드 입니다. private, public 등의 접근  제한자를 붙일 수 없고, 로컬 메서드 내부에서의 this 는 인스턴스 메서드에서의 this 와 다른것을 가리킨다는 것에 주의해야  합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Product<span style="color: #000000;">&#123;</span>
		prublic <span style="color: #339966; font-weight: bold;">function</span> Product<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span>
&nbsp;
			<span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span> <span style="color: #009900;">// 로컬 메서드</span>
				<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력: [object global]</span>
			<span style="color: #000000;">&#125;</span>
			doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">//자신을 소유하고 있는 메서드 내부에서만 호출할 수 있음</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력: [object Product]</span>
		<span style="color: #000000;">&#125;</span>
		doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 에러!! 호출 불가</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>또한 위와 같이 로컬 메서드에서의 this 는 [object global] 이 찍히므로 객체 내부의 인스턴스 변수와 메서드를 참조할 수가 없습니다.</p>
<h3>D. 초기화 순서</h3>
<p>자 이제 이 포스트의 핵심에 도달했습니다.<br />
클 래스가 초기화 될때 가장 우선시 되는 순서는 클래스 멤버 입니다. 클래스 변수와 클래스 메서드가 가장 먼저 초기화 되는거죠.  그리고 변수가 메서드 보다 먼저 초기화 됩니다. 로컬 멤버들은 인스턴스 멤버들 내부에 속하기 때문에 당연히 인스턴스 멤버들이  초기화 된 후의 순서 입니다.</p>
<ol>
<li>클래스 변수</li>
<li>클래스 메서드</li>
<li>인스턴스 변수</li>
<li>인스턴스 메서드</li>
<li>로컬 변수</li>
<li>로컬 메서드</li>
</ol>
<p>충분히 예상 할 수 있는 결과네요. 그런데 우리가 알아야 하는건 이 순서 자체가 아니라 순서가 이렇게 됨으로서 발생하는 제한사항에 대해서 입니다.</p>
<h4>D-1. 초기화의 상관 관계</h4>
<p>생각해 볼까요?<br />
클래스 변수가 가장 먼저 초기화 되기 때문에 클래스 변수, 즉 static 변수가 인스턴스 변수나 인스턴스 메서드를 참조하고 싶어도  걔네들은 아직 존재하지 않는 애들입니다. 클래스(설계도)는 있지만 객체는 아직 생성되기 전 시점이기 때문이죠.</p>
<div id="attachment_854" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-854 " title="init_step1" src="http://ufx.kr/blog/wp-content/uploads/2011/04/init_step1.png" alt="" width="590" height="257" /><p class="wp-caption-text">클래스 멤버가 초기화 되는 시점에 클래스 내부에는 (같은) 클래스 멤버외에는 아무것도 없습니다.</p></div>
<p>초기화가 끝난 후에 인스턴스 멤버들이 모두 생성되고 나면 런타임에서 참조할 수 있을텐데도, 컴파일 과정에서 아예 막혀 있습니다.  따라서 클래스 멤버에서 인스턴스 전용 키워드인 this 를 사용하면 컴파일 에러가 발생합니다.<sup>[<a href="http://ufx.kr/blog/853#footnote_0_853" id="identifier_0_853" class="footnote-link footnote-identifier-link" title="컴파일 에러 메세지는 다음과  같습니다. The this keyword can not be used in static methods. It can only be  used in instance methods, function closures, and global code.">01</a>]</sup> 객체가  생성되지도 않았는데 객체를 참조하려 할때 발생할 수밖에 없는 런타임 null 객체 에러를 컴파일 타임에 미리 봉쇄해 버리는 거죠.</p>
<div id="attachment_855" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-855    " title="init_step2" src="http://ufx.kr/blog/wp-content/uploads/2011/04/init_step2.png" alt="" width="590" height="257" /><p class="wp-caption-text">new 연산자를 이용해 객체가 생성된 이후에서야 인스턴스 멤버들이 등장합니다.</p></div>
<p>반대로 인스턴스 멤버를 초기화하는 시점에서는 이미 클래스 멤버들은 초기화가 끝나있는 상태이므로 인스턴스 멤버들은 얼마든지 클래스 멤버들을 참조할 수 있습니다. 물론 이때도 클래스 멤버는 인스턴스 멤버를 참조할 수 없습니다. (this 사용불가)</p>
<h4>D-2. 클래스 생성자 <a name="d2">#</a></h4>
<p>우리가 흔히 생성자라고 부르는 함수는 인스턴스 멤버의 생성자 함수입니다. 호스트 코드에서 그 생성자 함수를 호출하여  인스턴스화(객체화)를 할 수 있게 되죠. 뭐, 생성자에 static 키워드가 붙어 있지 않는 것만으로도 그것이 인스턴스 멤버임을  쉽게 짐작할 수 있습니다. 또한 생성자 함수를 호출하여 인스턴스화가 진행됨과 동시에 초기화가 이루어지게 되므로 인스턴스는 생성자  함수를 통해 초기화를 한다고 볼 수 있습니다.</p>
<p>그런데 클래스 멤버의 생성자 함수가 존재한다는 것을 알고 계십니까? 그러니까 static 생성자 함수라고 할 수 있겠네요.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> InitailizeTest
	<span style="color: #000000;">&#123;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;static 생성자 초기화 블럭&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> InitailizeTest<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;인스턴스 생성자 초기화 블럭&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이런 코드를 보신분도 있을것이고 처음보는 분들도 계실겁니다. 위와 같이 class 바디에 아무런 키워드나 접근 제한자 없이 중괄호를  열면 클래스가 생성되는 시점에<sup>[<a href="http://ufx.kr/blog/853#footnote_1_853" id="identifier_1_853" class="footnote-link footnote-identifier-link" title="인스턴스가 생성되는 시점이 아닙니다.">02</a>]</sup> 자동으로 실행되는 영역이 됩니다. 비교를 위해 바로  아랫 부분에 인스턴스 생성자 함수를 만들어 놓았습니다.</p>
<p>옆 동네인 Java 동네 에서는 이와 같이 클래스 바디에 중괄호로 펼쳐 놓은 부분은 인스턴스 초기화 영역 입니다. 우리  ActionScript 동네와는 다르죠. Java 에서 클래스 초기화 영역을 구성하려면 아래와 같이 클래스 바디에 static  키워드를 먼저 쓰고 중괄호를 열어야 합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// ActionScript 가 아닌 Java 코드 입니다.</span>
<span style="color: #000000; font-weight: bold;">class</span> JavaInitializeTest <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">static</span><span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Java 의 클래스 초기화 블럭</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// 인스턴스 초기화 블럭 (액션스크립트에서는 이 부분이 클래스 초기화 블럭)</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	JavaInitializeTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// 생성자 함수</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>그럼 이 클래스 초기화로 무엇을 할 수 있냐면, 인스턴스 생성자 함수에서 초기화를 하던것과 같은 발상을 하면 됩니다. Product 클래스로 이야기를 끌어 나가고 있으니까 계속 덧붙여 나가볼까요?</p>
<p>위와 같이 static 변수에 초기 값을 할당한다거나 static 객체에 이벤트 리스너를 달아주는 등을 예로 들 수 있겠죠.<br />
인스턴스 생성자에서 클래스 멤버들에 대한 참조가 가능하므로 인스턴스 초기화 단계로 넘겨서 클래스 멤버들의 초기화를 해도 문법상으로는  문제가 없긴 합니다만, 클래스 초기화가 필요했던 멤버는 클래스 초기화 영역에서 초기화를 끝내는게 올바른 방법 입니다. 이걸  인스턴스 초기화 단계로 끌고 내려가면 클래스 멤버쪽에서 어떤 행동이 다시 필요할때 에러가 생길 가능성이 높아집니다. 위에서도  썼듯이 클래스 멤버가 작동하는 시점에 인스턴스 멤버는 존재하지 않기 때문에 클래스 멤버가 참조해야 하는 인스턴스 객체는 null  입니다. 실제로 초기화 단계에서 static 멤버와 관련해서 일어나는 null 객체 에러의 대부분이 바로 이 문제 때문에  일어납니다. 제대로 이해하고 사용한다면 에러를 획기적으로 줄일 수 있겠죠?</p>
<p>지금까지 설명한 개념들을 하나의 예제 클래스로 만들어 보았습니다. trace() 출력되는 순서를 살펴보세요.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> InitailizeTest extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		static <span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> sv<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #000000;">&#123;</span> <span style="color: #004993;">call</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;static 변수 초기화&quot;</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span>;
		static <span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> obj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = getObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
		static <span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> getObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">return</span> <span style="color: #000000;">&#123;</span> key<span style="color: #000000; font-weight: bold;">:</span><span style="color: #990000;">&quot;static value&quot;</span> <span style="color: #000000;">&#125;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;static 생성자 초기화&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> sv <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력: [object Object]</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> obj.key <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력: static value</span>
			<span style="color: #009900;">//trace( this ); // Error: The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code.</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> iv<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #000000;">&#123;</span> <span style="color: #004993;">call</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;인스턴스 변수 초기화&quot;</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> obj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = getObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> InitailizeTest<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;인스턴스 생성자 초기화&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> obj.key <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력: instance value</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> getObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">return</span> <span style="color: #000000;">&#123;</span> key<span style="color: #000000; font-weight: bold;">:</span><span style="color: #990000;">&quot;instance value&quot;</span> <span style="color: #000000;">&#125;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>클래스 각 멤버들의 위아래 코딩 순서를 바꿔 봐도 출력되는 순서에는 변함이 없습니다. 따라서 초기화 순서는 클래스의 코딩 순서에  영향을 받지 않는다는 것도 알 수 있습니다. 다만, 초기화 순서에 따라서 클래스를 기술해 나가는 것이 가독성이 높을 수 밖에 없기  때문에 특별한 이유가 아니라면 초기화 순서에 따라 코딩을 해 나가는 것이 좋습니다.</p>
<ol class="footnotes"><li id="footnote_0_853" class="footnote">컴파일 에러 메세지는 다음과  같습니다. The this keyword can not be used in static methods. It can only be  used in instance methods, function closures, and global code.</li><li id="footnote_1_853" class="footnote">인스턴스가 생성되는 시점이 아닙니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/853/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>액션스크립트의 객체 재사용을 위한 오브젝트 풀(Object Pool)</title>
		<link>http://ufx.kr/blog/591</link>
		<comments>http://ufx.kr/blog/591#comments</comments>
		<pubDate>Wed, 01 Dec 2010 19:00:13 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[gabege collection]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[object pool]]></category>
		<category><![CDATA[가비지 컬렉션]]></category>
		<category><![CDATA[객체]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[동적]]></category>
		<category><![CDATA[재사용]]></category>
		<category><![CDATA[재활용]]></category>
		<category><![CDATA[정적]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=591</guid>
		<description><![CDATA[이 포스트는 &#8220;플래시 플레이어의 가비지 컬렉션(gabage collection)에 대한 이해&#8221; 로부터 이어지는 내용 입니다. A. Object Pool의 의미 객체 재사용 이라고 해서 뭐 엄청난 방법이 필요한 것은 아닙니다. 가장 쉽게 사용할 수 있는 방법으로는 Array 나 Vector 또는 Object 와 같은 컬렉션(Collection) 형태의 자료구조에 객체를 만들어 넣어두고 필요한 만큼 사용한 후, 필요없어진 객체를 다시 반납하는 방식으로 [...]]]></description>
			<content:encoded><![CDATA[<p>이 포스트는 &#8220;<a href="http://ufx.kr/blog/583" target="_self">플래시 플레이어의 가비지 컬렉션(gabage collection)에 대한 이해</a>&#8221; 로부터 이어지는 내용 입니다.</p>
<h3>A. Object Pool의 의미</h3>
<p>객체 재사용 이라고 해서 뭐 엄청난 방법이 필요한 것은 아닙니다. 가장 쉽게 사용할 수 있는 방법으로는 Array 나 Vector 또는 Object 와 같은 컬렉션(Collection) 형태의 자료구조에 객체를 만들어 넣어두고 필요한 만큼 사용한 후, 필요없어진 객체를 다시 반납하는 방식으로 로직을 구성하면 됩니다.</p>
<div id="attachment_577" class="wp-caption alignleft" style="width: 310px"><img class="size-full wp-image-577" title="object_pool" src="http://ufx.kr/blog/wp-content/uploads/2010/11/object_pool.jpg" alt="" width="300" height="232" /><p class="wp-caption-text">Object in Pool !!!</p></div>
<p>이러한 구조를 객체 풀 또는 오브젝트 풀(Object Pool) 이라고 부르고, 오브젝트 풀로부터 객체를 획득하는 행위를 풀링(pooling) 한다고 표현합니다.Pool은 우리도 흔히 사용하는 단어 입니다. [<a href="http://www.google.co.kr/dictionary?q=pool&amp;hl=ko&amp;sl=ko&amp;tl=en" target="_blank">구글 사전 링크</a>] 수영장의 그것을 일컫는 단어이기도 하고요, 제안서에서도 자주 &#8220;인력 풀&#8221; 과 같은 형태로 자주 등장합니다. 스타크래프트의 저그 종족에서 저글링을 생산하기 위한 기본 건물을 스포닝 풀(Spawning Pool : 산란못)이라고 부르죠. 어떠한 대상이 모여있는 특정 장소라는 원래의 뜻을 가지고 있습니다.</p>
<p><span id="more-591"></span><br />
오브젝트 풀을 다음과 같이 두 가지로 형식으로 구분할 수 있습니다.</p>
<h3>B. 정적 오브젝트 풀</h3>
<p>애플리케이션이 시작될때 미리 필요한 객체를 (정적으로) 만들어 놓고 시작하는 방식으로</p>
<ol>
<li> 필요한 객체 숫자가 정해져 있는 경우</li>
<li> 필요한 객체의 숫자가 아주 많지 않은 경우</li>
</ol>
<p>에 사용합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> FixedPoolTestDrive extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> FixedPoolTestDrive<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			createItem<span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 객체는 미리 생성</span>
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>Item = getItem<span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">3</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 3번 인덱스는 4번째 원소</span>
			item.<span style="color: #004993;">y</span> <span style="color: #000000; font-weight: bold;">+</span>= <span style="color: #000000; font-weight:bold;">100</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> createItem<span style="color: #000000;">&#40;</span> $num<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span>, item<span style="color: #000000; font-weight: bold;">:</span>Item;
			<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> $num; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span>
 			<span style="color: #000000;">&#123;</span>
 				item = <span style="color: #0033ff; font-weight: bold;">new</span> Item;<span style="color: #009900;">// 고정된 숫자만큼의 객체를 미리 생성</span>
 				item.<span style="color: #004993;">x</span> = <span style="color: #000000;">&#40;</span> item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #000000; font-weight:bold;">5</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000; font-weight: bold;">*</span> i;
 				<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;<span style="color: #009900;">// 더 이상 객체를 생성할 일이 없기 때문에 addChild()와</span>
 				_itemList<span style="color: #000000;">&#91;</span> i <span style="color: #000000;">&#93;</span> = item;<span style="color: #009900;">// 배열에 넣는것을 미리 다 해 놓는다.</span>
 			<span style="color: #000000;">&#125;</span>
 		<span style="color: #000000;">&#125;</span>
&nbsp;
 		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> getItem<span style="color: #000000;">&#40;</span> $index<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span>Item
 		<span style="color: #000000;">&#123;</span>
 			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> $index <span style="color: #000000; font-weight: bold;">&lt;</span>= _itemList.<span style="color: #004993;">length</span> <span style="color: #000000;">&#41;</span>
				<span style="color: #0033ff; font-weight: bold;">throw</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Error</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;Item 객체의 인덱스는 0 부터 &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #000000;">&#40;</span> _itemList.<span style="color: #004993;">length</span> <span style="color: #000000; font-weight: bold;">-</span> <span style="color: #000000; font-weight:bold;">1</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #990000;">&quot;번 까지 있고 &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> $index <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #990000;">&quot;번은 목록에 존재하지 않는 인덱스입니다.&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">return</span> _itemList<span style="color: #000000;">&#91;</span> $index <span style="color: #000000;">&#93;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h3>C. 동적 오브젝트 풀</h3>
<p>애플리케이션이 시작되는 시점에는 객체의 숫자가 0으로 시작하고 요청이 들어오면 필요한 만큼 new 로 생성해서 사용하는 방식으로</p>
<ol>
<li> 필요한 객체의 숫자를 정할 수 없는 경우</li>
<li> 필요한 객체의 숫자가 많은 경우</li>
<li> 또는 객체의 사용 갯수의 폭이 실행때마다 상당히 다른 경우(어떤 경우는 조금 사용하고, 어떤 경우는 많이 사용하는)</li>
</ol>
<p>에 사용하면 적합 합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> DynamicPoolTestDrive extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> DynamicPoolTestDrive<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">index</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> = <span style="color: #000000; font-weight:bold;">3</span>;
			<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>Item = getItem<span style="color: #000000;">&#40;</span> <span style="color: #004993;">index</span> <span style="color: #000000;">&#41;</span>;
			item.<span style="color: #004993;">y</span> <span style="color: #000000; font-weight: bold;">+</span>= <span style="color: #000000; font-weight:bold;">100</span>;
			item.<span style="color: #004993;">x</span> = <span style="color: #000000;">&#40;</span> item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #000000; font-weight:bold;">5</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #004993;">index</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> getItem<span style="color: #000000;">&#40;</span> $index<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span>Item
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 요청한 인덱스에 해당하는 _itemList 배열을 변수에 대입. 인덱스에 해당하는 원소가 존재할수도 있고 아닐수도 있다.</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>Item = _itemList<span style="color: #000000;">&#91;</span> $index <span style="color: #000000;">&#93;</span>;
&nbsp;
			<span style="color: #009900;">// 위의 변수에 대입된 객체가 null 이라면 아래의 조건문이 실행된다. ( not 연산자 ! 로 조건을 걸었으므로. )</span>
			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight: bold;">!</span> item <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				item = <span style="color: #0033ff; font-weight: bold;">new</span> Item; <span style="color: #009900;">// 객체를 생성</span>
				<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// addChild() 하고</span>
				_itemList<span style="color: #000000;">&#91;</span> $index <span style="color: #000000;">&#93;</span> = item; <span style="color: #009900;">// 해당하는 배열 인덱스에 넣은후 return 해준다.</span>
			<span style="color: #000000;">&#125;</span>
			<span style="color: #0033ff; font-weight: bold;">return</span> item;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>어떻습니까? 간단한 오브젝트 풀이지만 이것으로 얻어지는 효과는 상당히 뛰어납니다.<br />
비행기 슈팅게임을 만드는 경우를 예로 들어볼까요? 총알을 발사할 때마다 new Bullet() 을 하여 계속 총알을 만든다면 계속 메모리 사용량이 증가할 수 밖에 없겠죠. 총알이라면 크기가 작으니 그나마 다행입니다. 적 비행기라면 어떨까요?<br />
어차피 비행기가 총알을 발사하는 한 화면에서 동시에 공존하는 총알의 최대 갯수가 존재합니다. 그만큼의 총알만 미리 만들어 놓고 총알이 화면 밖으로 나가서 더 이상 의미가 없게 되면 다시 회수에서 재사용 하는 것입니다.<br />
메모리 사용량은 일정 수준에서 더 이상 늘어나지 않게 되고 최종보스를 만날때까지 안정적인 동작을 할 수 있겠죠.</p>
<p>한 가지 주의해야 할 점은, 현재 새로 사용하고자 하는 인덱스의 객체가 사용중인지 아닌지 판단할 수 있는 장치를 마련해야 하는 점입니다. 사용중인 객체를 마구 끌어다 쓰면 곤란해지겠죠. 객체 내부의 변수, 예컨대 public var isIdle:Boolean 과 같이 플래그를 두어 구분 하는 등의 방법을 사용하면 되겠습니다.</p>
<h3>D. 오브젝트 풀 클래스</h3>
<p>위에서 알아본 컬렉션을 이용한 오브젝트 풀은 호스트 코드에 섞여 있는 형태이기 때문에, 오브젝트 풀이 존재하는 클래스의 코드가 매우 길어서 가독성이 떨어진다거나, 객체들이 복잡한 구조를 가지고 있는 애플리케이션 이라거나 캡슐화를 업격하게 적용해야의하는 경우에는 사용하기 어려울 때가 있습니다. 이런 고민을 여러분만 했을리는 없겠죠. 그래서 전세계 여러 개발자들이 오브젝트 풀을 클래스 화 하여 관리하는 방법을 사용합니다.</p>
<p>액션스크립트에서 사용할 수 있는 오브젝트 풀 클래스 중에서는 우리나라 카페쪽 커뮤니티나 개인 개발자 블로그 등에서 여러번 소개된 바 있는 polygonal.de 의 라이브러리가 가장 유명합니다. 폴리고날에서 2008년 발표한 ObjectPool 라이브러리를 이 [<a href="http://lab.polygonal.de/2008/06/18/using-object-pools/ " target="_blank">링크</a>]에서 다운받아 사용해 볼 수 있습니다.</p>
<p>이 글을 쓰기로 처음 마음먹은 무렵에는 저 역시 폴리고날의 오브젝트 풀 클래스를 여러분에게 소개하고 원리와 사용방법을 기술하려 했지만, 사실 제가 아니더라도 이미 다른 분들이 소개하고 있는데다가, 폴리고날 오브젝트 풀의 코드를 분석해 보고 난 후 코드를 분석하는것 자체가 의미가 별로 없다는 것을 깨달았습니다. 여러분도 소스코드를 보시면 느끼시겠지만, 이해하기 어렵습니다. 사실 이해할 필요 없이 제대로 동작하기만 해도 무방하죠. 그래서 더더욱&#8230;</p>
<p>객체의 재사용을 다룬 이 연속 포스팅들은 원래 &#8220;<a href="http://cafe.naver.com/pfgroup/1088" target="_blank">제3회 PFG 트렌드 공유 오픈세미나</a> &#8221; 의 세션 발표의 목적으로 초고가 쓰여진 것인데, 발표 전날 방향을 살짝 바꿔서 오브젝트 풀을 간단하게 제작해보기로 했습니다.<br />
아래의 오브젝트 풀은 여러분에게 동작 방식을 설명하기 위해 아주 기본적인 기능만을 가지고 있습니다. 누구든지 자유롭게 수정하여 사용하실 수 있습니다. (단, 수정하실 경우에는 제 이름을 원저자로, 수정하신 분을 수정저자 정도로 표기해 주시면 고맙겠습니다.)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">DisplayObjectContainer</span>;
	<span style="color: #3f5fbf;">/**
	 * Simple Object Pool Class with DisplayObjectContainer
	 * @author 원종선[세계의끝] cuebrick[ at ]gmail.com http://ufx.kr/blog
	 */</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ObjectPool
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _class<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Class</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _activeList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _deactiveList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _container<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">DisplayObjectContainer</span>;
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 할당받을 클래스(형:type)을 지정한다.
		 * @param	$class
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> allocation<span style="color: #000000;">&#40;</span> $class<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Class</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			_class = $class;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 객체를 부모 컨테이너에 붙여서 반환받고 싶다면 설정한다.
		 * @param	$container
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> setContainer<span style="color: #000000;">&#40;</span> $container<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">DisplayObjectContainer</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			_container = $container;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 이 메서드를 이용해 객체를 요청한다.
		 * _deactiveList 배열을 조회하여 객체가 존재하면 반환하고, 없으면 새로 생성하여 반환해준다.
		 * 새로 생성하여 반환해준 경우 객체를 _activeList 에 push 해 놓는다.
		 * @return
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> getInstance<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:*</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:*</span>;
			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> _deactiveList.<span style="color: #004993;">length</span> == <span style="color: #000000; font-weight:bold;">0</span> <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				instance = <span style="color: #0033ff; font-weight: bold;">new</span> _class<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
				<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> _container <span style="color: #000000;">&#41;</span>
					_container.<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
			<span style="color: #0033ff; font-weight: bold;">else</span>
			<span style="color: #000000;">&#123;</span>
				instance = _deactiveList.<span style="color: #004993;">shift</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
&nbsp;
			_activeList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">return</span> instance;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 사용이 끝난 객체를 오브젝트 풀에 반환해준다.
		 * 반환하면 _deactiveList 배열에 등록되고, 다시 사용할 수 있는 상태로 바뀐다.
		 * @param	$instance
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> returnInstance<span style="color: #000000;">&#40;</span> $instance<span style="color: #000000; font-weight: bold;">:*</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:*</span>;
			<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span> <span style="color: #000000;">&#40;</span> instance <span style="color: #0033ff; font-weight: bold;">in</span> _activeList <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> instance == $instance <span style="color: #000000;">&#41;</span>
				<span style="color: #000000;">&#123;</span>
					<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;instance 반환되었음 :&quot;</span>, $instance <span style="color: #000000;">&#41;</span>;
					_deactiveList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> $instance <span style="color: #000000;">&#41;</span>;
					_activeList.<span style="color: #004993;">splice</span><span style="color: #000000;">&#40;</span> _activeList.<span style="color: #004993;">indexOf</span><span style="color: #000000;">&#40;</span> $instance <span style="color: #000000;">&#41;</span>, <span style="color: #000000; font-weight:bold;">1</span> <span style="color: #000000;">&#41;</span>;
				<span style="color: #000000;">&#125;</span>
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 현재 사용중인 객체들의 목록을 조회
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #0033ff; font-weight: bold;">get</span> activeList<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> <span style="color: #000000;">&#123;</span> <span style="color: #0033ff; font-weight: bold;">return</span> _activeList; <span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 현재 사용할 수 있는 객체들의 목록을 조회
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #0033ff; font-weight: bold;">get</span> deactiveList<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> <span style="color: #000000;">&#123;</span> <span style="color: #0033ff; font-weight: bold;">return</span> _deactiveList; <span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>클래스 내부에 사용중 객체 목록과 미사용중 객체 목록이 배열로 두개 있고, 호스트 코드에서 getInstance() 메서드로 요청하면 미사용중 객체 목록 배열에서 반환해주거나, 노는 객체가 없으면 새로 만들어 반환해 주는 형태입니다. 호스트 코드가 대여하거나 반납한 객체는 그에 알맞은 상태의 배열로 옮겨 놓는 방식으로 간단하게 구현하였습니다. public 메서드에 주석을 자세하게 달아 놓았으므로 그 밖의 코드에 대한 별도의 설명은 필요하지 않을것 같습니다.</p>
<p>호스트 코드에서는 이렇게 사용하겠죠.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// 오브젝트 풀 객체를 생성</span>
<span style="color: #6699cc; font-weight: bold;">var</span> _pool<span style="color: #000000; font-weight: bold;">:</span>ObjectPool = <span style="color: #0033ff; font-weight: bold;">new</span> ObjectPool;
&nbsp;
<span style="color: #009900;">// MyClass 형의 객체로 클래스 할당</span>
_pool.allocation<span style="color: #000000;">&#40;</span> MyClass <span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// 풀에 객체 요청하고 변수에 대입</span>
<span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span>MyClass = _pool.getInstance<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// 객체를 컨테이너에 붙임</span>
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// 사용이 끝나면 풀에 객체를 반환함</span>
<span style="color: #004993;">removeChild</span><span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;
_pool.returnInstance<span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>pool 에다가 getInstance() 해서 객체를 새로 받아오다니, 마치 손안대고 코를 푸는것 같은 느낌같지 않습니까?</p>
<h3>E. 객체 재사용의 효과</h3>
<p>객체를 재사용하게 되면 다음의 몇 가지 긍정적인 효과를 기대해 볼 수 있습니다.</p>
<ol>
<li>런타임 성능 향상 (Improve run-time performance)</li>
<li>메모리 누출 방지 (Prevent memory leak)</li>
<li>안정적인 동작 (Running stable)</li>
</ol>
<h4>E-1. 런타임 성능 향상</h4>
<p>애플리케이션이 시작, 초기화 하면서 사용될 객체를 모두 만들어 놓은 경우라면, 런타임에 new 를 연산하느라 버벅일 필요가 없겠죠. 따라서 런타임에 성능 향상이 일어날 수 있습니다. 동적으로 풀을 구성한 경우라도 어쨌건 무분별하게 객체를 생성할 가능성이 줄어들므로 마찬가지로 성능 향상을 꾀할 수 있겠습니다.</p>
<h4>E-2. 메모리 누출 방지</h4>
<p>어딘가에 버려졌지만 addEventListener 가 달려있다는 죄로 GC(가비지 컬렉션)가 수집도 안해가는 불쌍한 객체들이 없어지게 되므로, 메모리 누출 현상이 획기적으로 줄어들 가능성이 있습니다.</p>
<h4>E-3. 안정적인 동작</h4>
<p>쓸데 없이 객체를 생성하지 않고 계속 재사용 하게 되므로, GC가 돌아도 별로 수거할 것이 없게 될 가능성이 높습니다. &#8220;가비지 컬렉션에 대한 이해&#8221; 편에서 설명한것과 같이 GC가 돌게 되면 (특히 플래시 플레이어 같이 싱글 쓰레드라면 더욱더) 모든 동작을 멈추고 GC를 돌리게 되므로 플래시 애플리케이션이 순간적으로 멈칫거리는 현상이 발생하게 되는데, 오브젝트 풀을 사용한다면 GC가 할일이 거의 없게 되므로 전체적으로 랙이 줄어드는 안정적인 동작을 기대해 볼 수 있습니다.</p>
<h4>그런가 하면</h4>
<ol>
<li>전체적인 메모리 사용 총량은 약간 올라가는 경향이 있고,</li>
<li>에러발생율이 낮아지는 효과가 있습니다. (특히 null 객체 에러)</li>
<li>또한 GC를 사용 하지 않는 것을 전제로 하기 때문에 메모리 관리를 개발자가 직접 해야 하는 귀찮음 정도는 감수해야겠죠. (머릿속으로 메모리를 계산)</li>
</ol>
<p>이렇게 액션스크립트에서의 객체 재사용(재활용) 과 오브젝트 풀에 관한 세 개의 연속 포스팅을 살펴보았습니다. 객체를 재사용 하는 것 정도는 객체지향 프로그래밍을 하는 개발자들에게는 기본기라고 할 수 있을 정도 이므로 여러분들도 꼭 알아두시고, 실천에 옮겨, 프로그램의 수준을 한 단계 높이길 바라겠습니다.</p>
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/591/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>플래시 플레이어의 가비지 컬렉션(gabage collection)에 대한 이해</title>
		<link>http://ufx.kr/blog/583</link>
		<comments>http://ufx.kr/blog/583#comments</comments>
		<pubDate>Wed, 01 Dec 2010 00:00:30 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[compact]]></category>
		<category><![CDATA[gabege collection]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[mark]]></category>
		<category><![CDATA[object pool]]></category>
		<category><![CDATA[sweep]]></category>
		<category><![CDATA[가비지 컬렉션]]></category>
		<category><![CDATA[객체]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[재사용]]></category>
		<category><![CDATA[재활용]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=583</guid>
		<description><![CDATA[이 포스트는 &#8220;액션스크립트로 하는 객체 재사용(재활용)과 오브젝트 풀(Object Pool) &#8211; 개요&#8221; 로부터 이어지는 내용 입니다. A. 가비지 컬렉션 일반론 Gabage Collection Overview 프로그래밍을 하면서 사용한 객체는 메모리를 소비해야 하기 때문에 운영체제에서 빌려와서 사용하게 됩니다. 메모리를 빌려와 그 공간에 객체를 기록하는 행위를 할당(allocation) 이라고 합니다. 그리고 객체를 사용한 후 더이상 필요가 없어지게 되면 객체를 운영체제에 반납하는 [...]]]></description>
			<content:encoded><![CDATA[<p>이 포스트는 &#8220;<a href="http://ufx.kr/blog/570" target="_self">액션스크립트로 하는 객체 재사용(재활용)과 오브젝트 풀(Object Pool) &#8211; 개요</a>&#8221; 로부터 이어지는 내용 입니다.</p>
<h3>A. 가비지 컬렉션 일반론 Gabage Collection Overview</h3>
<p>프로그래밍을 하면서 사용한 객체는 메모리를 소비해야 하기 때문에 운영체제에서 빌려와서 사용하게 됩니다. 메모리를 빌려와 그 공간에 객체를 기록하는 행위를 할당(allocation) 이라고 합니다. 그리고 객체를 사용한 후 더이상 필요가 없어지게 되면 객체를 운영체제에 반납하는 절차를 거쳐야 합니다. 마치 도서관에서 책(객체)을 대출한 후 열람실(메모리)에서 열람하는 것과 같다고 볼 수 있습니다.</p>
<p>그런데 프로그래밍이라는 것이 컴퓨터가 하는것이 아니라 개발자라는 사람이 하는 것이라, 운영체제에서 빌려온 메모리를 반환하지 않고 빼먹는 개발자가 있기도 합니다. 프로그램이 짧은 시간 동안 실행되고 종료 되는 것이라면 큰 문제는 아니지만, 서버용 프로그램과 같이 프로그램이 실행 한 후 오랜 시간 동안 실행 상태를 유지해야 하는 경우에는 메모리에 더 이상 사용하지 않게된 메모리들이 점점 쌓이는 한편, 새로운 메모리는 계속 요구 되기 때문에 언젠가는 메모리가 꽉 자서 옴짝 달싹 할 수 없게 됩니다. 이런 것을 메모리 유출(memory leek) 현상이라고 하여 프로그램 에러의 가장 치명적인 원인이 됩니다.</p>
<p><a href="http://ufx.kr/blog/wp-content/uploads/2010/11/Trashfull.png"><img class="alignleft size-full wp-image-588" title="Trashfull" src="http://ufx.kr/blog/wp-content/uploads/2010/11/Trashfull.png" alt="" width="150" height="150" /></a>그래서 현대의 고급 프로그래밍 언어에는 이런 메모리 반납 과정을 자동으로 처리해 주는 Gabage Collection (이하 GC) 이라는 것이 생겨났습니다. 프로그래머가 사용한 후 필요 없어진 객체들은 GC가 정기적으로 수거하고 메모리에서 소멸시켜버려 다시 메모리를 사용할 수 있는 상태로 만들어주는거죠. 위에서 한 도서관의 비유를 계속 이어나가자면 가비지 컬렉션은, 우리가 그 존재를 눈치채기는 쉽지 않지만, 더이상 아무도 읽지 않거나 너무 낡아 책으로서의 가치가 없어진 것들을 수거해서 처리하는 사서에 비할 수 있을것 같습니다.</p>
<p>그러나 GC는 메모리 반환을 하기 귀찮아 하는 게으른 프로그래머를 위한 도구라기 보다는, 프로그래머가 메모리 반환 같은 단순한 일에 신경쓰지 않고 보다 큰 개념의 로직이나 구조적인 프로그래밍에 집중할 수 있도록 도와주는 역할을 한다고 보는것이 타당합니다.</p>
<p><span id="more-583"></span></p>
<h3>B. Mark, Sweep and Compact</h3>
<p>GC가 동작하는 방식을 그림으로 표현해 보겠습니다.</p>
<div id="attachment_585" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-585 " title="mark_sweep_compact" src="http://ufx.kr/blog/wp-content/uploads/2010/11/mark_sweep_compact.png" alt="" width="590" height="442" /><p class="wp-caption-text">Mark, Sweep &amp; Compact</p></div>
<ol>
<li>Mark &#8211; 참조되고 있지 않은 객체를 표시(mark) 한 후,</li>
<li>Sweep &#8211; 표시된 객체를 쓸어(sweep) 버리고,</li>
<li>Compact &#8211; 중간중간 구멍이 뚫려 있는 메모리 공간을 남아있는 객체를 스스슥 이동해서 디스크 조각모음을 하듯 공간을 확보합니다.<sup>[<a href="http://ufx.kr/blog/583#footnote_0_583" id="identifier_0_583" class="footnote-link footnote-identifier-link" title="Java 에서는 이 compact 과정이 존재하는데, 플래시 플레이어가 이 과정을 수행하는지는 확실히 알려져 있지 않습니다.">01</a>]</sup></li>
</ol>
<p>이 과정을 개발자가 신경쓰지 않아도 플래시 플레이어의 GC가 수행합니다. 상당히 편리하겠죠? 객체가 변수에 대입되거나, addEventListener() 메서드가 달려있거나 하는 등의 참조가 되어있다면 GC가 mark 를 하지 않습니다. mark 가 되지 않으면 sweep 되지 않으므로 그 객체는 GC에 의해 삭제당할 가능성이 없는 상태가 됩니다.<br />
위의 내용을 Grant Skinner가 시뮬레이션 할 수 있게 만들어 놓은 <a href="http://www.gskinner.com/blog/archives/2006/09/garbage_collect.html" target="_blank">[링크]</a> 를 확인해 보세요.</p>
<p>그러나 지금까지의 설명은 객체지향 프로그래밍의 GC에 대한 일반론에 불과합니다. 액션스크립트에서는 이와같은 일반론에 더해지는 몇 가지 특수한 상황들이 존재합니다.</p>
<h3>C. 액션스크립트 개발자의 입장에서 본 GC</h3>
<p>액션스크립트 역시 Java 의 연장선상에 있는 현대의 고급 프로그래밍 언어에 속하기 때문에 GC를 이용한 메모리 회수 방식을 사용합니다. 그런데 플래시 개발자들이 알아야만 하는 몇 가지 사항이 더 있습니다.</p>
<h4>C-1. GC를 강제로 실행시킬 수 없다.</h4>
<p>GC는 운영체제가 플래시 플레이어에게 할당한 일정 분량의 메모리가 고갈되어갈 무렵에 실행되기 때문에 그 실행 시점을 정확히 알 수 없습니다. 또한, 버그로 동작되는 상황을 제외하고는 개발자가 GC의 동작을 시작시킬 수 없습니다. NetConnection 객체를 고의로 두번 호출하면 이 객체를 회수하기 위해 GC가 동작하게 되고 try&#8230;catch로 감싸놓으면 런타임 에러가 발생하지 않게 되는 버그가 있습니다만, 정상적인 처리 방법이 아닐뿐더러 Adobe 에 의해 언제 패치될지도 모르므로 사용하지 않는것이 좋습니다.</p>
<h4>C-2. GC가 도는 시점이 문제.</h4>
<p>대부분의 플래시 플레이어는 웹 브라우저에 플러그인 형태로 실행되기 때문에 플래시 답게 항상 가벼운 동작을 기대하지만, 실제로 GC가 돌기 시작하는 시점은 이미 무거워질대로 무거워져 물기를 흠뻑 머금은 스펀지와 같은 상황일때가 되고 나서인 경우가 대부분 입니다. 우리가 플래시에게 기대하는 것은 이런것이 아니겠죠.</p>
<h4>C-3. GC의 수거대상이 되게 하기 위한 준비작업의 번거로움.</h4>
<p>객체를 가비지 컬렉션 대상이 되게 하기 위해서는 변수가 가리키는 모든 참조 제거, 객체에 붙여놓은 이벤트리스너 모두를 제거한 후, 변수에 null 을 대입해야 합니다. 이렇게 글로 표현하는것은 쉽지만, 실제 코드상에서는 이 객체가 어디서 몰래 참조되고 있는지 알 수 없는 경우도 꽤 됩니다. 게다가 이런 절차는 네이티브 개발자 출신이 아닌 경우가 많은 플래시 개발자의 입장에서는 번거롭게 느껴지기 마련이고, 그냥 내버려 두는 경우가 대부분이죠.</p>
<h4>C-4. GC가 돌아도 문제.</h4>
<p>우여곡절끝에 GC가 돌아도 문제가 여전히 남아 있습니다. GC가 실행될때는 프로그램이 일시적으로 중단되는 현상을 발견하게 됩니다. GC 대상이 많은 경우라면 체감할 수 있을 정도죠. 게다가 플래시 플레이어는 기본적으로 싱글 쓰레드 이기 때문에 프로그램 실행을 모두 일시 중단하고 GC를 돌린 후 다시 프로그램을 실행 하게 되므로 멈칫거리는 현상이 더욱 잘 느껴집니다.</p>
<h3>D. Gabage Collection vs. Object Pool</h3>
<p>플래시로 만들어진 대부분의 일반적인 웹 애플리케이션들은 GC에게 객체의 수명관리를 맡겨도 무방합니다. 어차피 플래시 애플리케이션은 대부분 웹 브라우저에 플러그인 형태로 보여지게 되고, 플래시가 차지하고 있던 메모리는 브라우저가 종료되는 시점에 동시에 회수되는 브라우저 의존적인 형태라 실행되는 지속 시간이 그리 길지 않기 때문이죠.</p>
<p>그러나 게임과 같이 생성해야 하는 객체의 숫자가 많고, 지속시간도 대체로 긴 편이면서, 그 객체가 차지하는 메모리 크기가 큰 경우에는 GC 보다는 객체 풀(Object Pool) 방식으로 객체를 재활용 관리하는 것이 보다 좋은 선택이라 할 수 있습니다.</p>
<p>객체 풀 방식에 대해서는 &#8220;<a href="http://ufx.kr/blog/591">액션스크립트의 객체 재사용을 위한 오브젝트 풀(Object Pool)</a>&#8221; 에서 이어집니다.</p>
<ol class="footnotes"><li id="footnote_0_583" class="footnote">Java 에서는 이 compact 과정이 존재하는데, 플래시 플레이어가 이 과정을 수행하는지는 확실히 알려져 있지 않습니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/583/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>액션스크립트로 하는 객체 재사용(재활용)과 오브젝트 풀(Object Pool) &#8211; 개요</title>
		<link>http://ufx.kr/blog/570</link>
		<comments>http://ufx.kr/blog/570#comments</comments>
		<pubDate>Tue, 30 Nov 2010 09:29:25 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[gabege collection]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[가비지 컬렉션]]></category>
		<category><![CDATA[객체]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[재사용]]></category>
		<category><![CDATA[재활용]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=570</guid>
		<description><![CDATA[플래시가 처음 등장했을 무렵의 액션스크립트는 자바스크립트 수준의 쉬운 언어였기 때문에 그만큼 장벽이 낮게 느껴져 많은 숫자의 플래시 개발자들이 등장할 수 있었습니다. 네비게이션 바나 롤링 배너와 같은 간단한 작업물 만을 만들던 시절에는 객체지향적인 프로그래밍 방법론은 그닥 중요한 이슈가 아니었습니다. 되려, 플래시가 처음부터 현재 AS3.0 과 같은 형태로 시작했다면 현재 현업에서 일하고 있는 플래시 개발자 중 꽤 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-600" title="recycle" src="http://ufx.kr/blog/wp-content/uploads/2010/11/recycle.jpg" alt="" width="254" height="245" />플래시가 처음 등장했을 무렵의 액션스크립트는 자바스크립트 수준의 쉬운 언어였기 때문에 그만큼 장벽이 낮게 느껴져 많은 숫자의 플래시 개발자들이 등장할 수 있었습니다. 네비게이션 바나 롤링 배너와 같은 간단한 작업물 만을 만들던 시절에는 객체지향적인 프로그래밍 방법론은 그닥 중요한 이슈가 아니었습니다. 되려, 플래시가 처음부터 현재 AS3.0 과 같은 형태로 시작했다면 현재 현업에서 일하고 있는 플래시 개발자 중 꽤 많은 숫자가 아마 다른일을 하고 있을 것입니다. 시각적이고 쉬운 접근 방식이 브라우저의 일개 플러그인에 불과한 플래시가 이 정도 수준의 개발자 인구를 가지게 하는 원인이 되기도 했죠.</p>
<p>그러나 사용자들의 웹 애플리케이션에 대한 기대치가 높아지고 플래시로 만들어진 다양한 형태의 애플리케이션이 등장함으로서 보다 높은 차원의 프로그래밍 스킬이 요구되는 경우가 생겼습니다. 객체 재사용(재활용) 은 그런 한 단계 높은 차원의 프로그래밍 스킬 중 하나라고 볼 수 있는데요, 객체를 재사용 하는 방법에 대해 몇 개의 연속 포스팅으로 알아보겠습니다.</p>
<p>제가 이 주제에 대해 포스팅을 하게 된 직접적인 계기가 된 일이 있습니다. 얼마전 액션스크립트 카페에 아래와 같은 질문이 올라왔었습니다.<sup>[<a href="http://ufx.kr/blog/570#footnote_0_570" id="identifier_0_570" class="footnote-link footnote-identifier-link" title="http://cafe.naver.com/flashactionscript/53831">01</a>]</sup></p>
<p><span id="more-570"></span></p>
<h3>A. 질문 사례 (Case Study)</h3>
<p>가비지컬렉션에 대한 문서들을 수집해서 보는중인데<br />
대부분 재활용을 극대화하라는 내용으로 끝을 내더라구요.(한계?!)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Sprite 변수</span>
<span style="color: #6699cc; font-weight: bold;">var</span> myObject<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span>;
&nbsp;
<span style="color: #3f5fbf;">/* 등록 */</span>
myObject = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span>myObject<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #3f5fbf;">/* 삭제 */</span>
<span style="color: #004993;">removeChild</span><span style="color: #000000;">&#40;</span>myObject<span style="color: #000000;">&#41;</span>;
myObject = <span style="color: #0033ff; font-weight: bold;">null</span>;
&nbsp;
<span style="color: #3f5fbf;">/* 재활용?! */</span>
myObject = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span>myObject<span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>이런식으로 사용하라는 건가요?<br />
아니면 다른 좋은 예가 있을까요?</p>
<h4 style="text-align: center;">위와 같은 질문에 제가 아래와 같이 답변을 달았습니다.</h4>
<p>한계가 아니라 그렇게 하는것이 객체지향 언어의 기본입니다.<br />
플래시가 워낙에 언어적 기반이 없는 초보 개발자들이 많은 동네다 보니 이런 부분이 덜 중요하게 인식되는것 뿐이죠.</p>
<p>예로드신 방법은 재활용에 해당하지 않습니다.<br />
재활용은 변수를 재활용하는것이 아니라 객체를 재활용하는 것이거든요.<br />
변수는 백만개 만들어도 성능에 크게 지장 없습니다.<br />
그러나 객체를 백만개 만들면 플래시가 뻗어버리겠죠.</p>
<p>아래와 같은 클래스가 있습니다. 잘 살펴보세요. 어떤 구조를 가졌는지..</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// MyObject 클래스</span>
<span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
    <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MyObject extends <span style="color: #004993;">Sprite</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _form<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">0</span>;
&nbsp;
        <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> MyObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 최초 실행시에 초기화</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
        <span style="color: #000000;">&#123;</span>
            _form = <span style="color: #000000; font-weight:bold;">0</span>; <span style="color: #009900;">// 변수를 초기화</span>
            <span style="color: #009900;">// 그 밖의 각종 초기화 코드 (시각적인것을 포함하여 xml 등의 데이터 등도 초기화)</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> setForm<span style="color: #000000;">&#40;</span> $form<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
        <span style="color: #000000;">&#123;</span>
            _form = $form; <span style="color: #009900;">// 변수에 저장하고 그것을 이용해</span>
            <span style="color: #009900;">// 이 객체의 여러가지 형태를 설정 (아마도 시각적인것)</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>그리고 호스트코드에서 아래와 같이 사용합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// 변수</span>
<span style="color: #6699cc; font-weight: bold;">var</span> myObject<span style="color: #000000; font-weight: bold;">:</span>MyObject; <span style="color: #009900;">// Sprite 가 아니라 MyObject 클래스 입니다. (요주의, 아래에 설명 되어있음)</span>
&nbsp;
<span style="color: #3f5fbf;">/* 생성 */</span>
myObject = <span style="color: #0033ff; font-weight: bold;">new</span> MyObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// new 는 여기서 한번만 합니다.</span>
myObject.setForm<span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">3</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 3번 형태로 사용</span>
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span>myObject<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #3f5fbf;">/* 재활용 */</span>
myObject.<span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 초기화시킴</span>
myObject.setForm<span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">2</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 2번 형태로 재사용</span>
&nbsp;
<span style="color: #3f5fbf;">/* 삭제, (그러나 같은 유형의 객체가 다시 등장할것 같으면 삭제하지 않음) */</span>
<span style="color: #004993;">removeChild</span><span style="color: #000000;">&#40;</span>myObject<span style="color: #000000;">&#41;</span>;
myObject = <span style="color: #0033ff; font-weight: bold;">null</span>;</pre></td></tr></table></div>

<p>Sprite 따위를 왜 재사용해야하나 하는 생각 때문에 질문을 작성하신듯 한데요,<br />
Sprite 에 graphics 패키지를 이용해 그림이라도 열나게 그리지 않는 이상, Sprite 형의 객체에 초기화 할 일은 많지 않겠죠.<br />
코드로 전부 설명해 놓았으니 여러번 읽어보세요.</p>
<p>new 를 단 한번 한다는 것이 재활용의 포인트 입니다.<br />
좀더 깊은 곳으로 가면, new 조차도 다른 객체에 의뢰하여 해당 클래스 안에서는 new 가 필요 없게도 하는 경우가 있습니다.</p>
<h3>B. new 연산자.</h3>
<p>프로그래밍에서 객체를 생성한다는 것은 좀 남다른 의미를 가집니다. 바로 무(無)에서 유(有)를 창조해 내는 과정이기 때문이죠. 액션스크립트에서는 class 를 설계도 삼아 new 연산자를 이용해 실제 객체를 생성하게 됩니다. 문제는 이 과정이 컴퓨터의 자원을 가장 많이 사용하는 연산중 하나라는 사실이죠.</p>
<p>게다가 액션스크립트에서 다루는 객체들의 대다수는 DisplayObject 를 상속한 객체들이기 때문에, 객체 하나하나의 데이터 크기가 큰 편이라, 객체를 재사용 하면 경우에 따라 그 효과가 눈에 보일정도로 좋아지게 됩니다.</p>
<p>위의 질문 내용으로 다시 올라가 코드를 다시 보면, 객체를 재활용 하고 있지 않다는 것을 알 수 있습니다. 1번 라인에서 선언된 변수 myObject 는 가장 아랫 라인까지 재활용 하고 있지만 객체는 두 번 new Sprite() 하고 있죠. 즉, 변수는 재활용을 하고 있는데, 정작 객체는 이전 객체를 버리고 새로 객체를 만들어 사용하고 있습니다. 두 번째 객체를 생성하여 myObject 변수에 대입한 순간에 이전에 만든 객체는 참조할 수 있는 방법을 잃어버려 개발자는 이 객체에 두 번 다시 접근할 수 없습니다. 더군다나 이 객체에 addEventListener() 라도 달려있다면 쓰레기(gabage) 상태로 메모리에 남아 플래시 플레이어가 종료될때까지 계속 살아있게 됩니다.</p>
<p>이 쓰레기에 대한 정체를 파악해 보고자, 다음 내용은 &#8220;<a href="http://ufx.kr/blog/583">플래시 플레이어의 가비지 컬렉션(gabage collection)에 대한 이해</a>&#8221; 로 이어집니다.</p>
<ol class="footnotes"><li id="footnote_0_570" class="footnote"><a href="http://cafe.naver.com/flashactionscript/53831" target="_blank">http://cafe.naver.com/flashactionscript/53831</a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/570/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>예제를 통해 쉽게 풀어보는 OOP의 다형성 (Polymorphism)</title>
		<link>http://ufx.kr/blog/539</link>
		<comments>http://ufx.kr/blog/539#comments</comments>
		<pubDate>Sun, 24 Oct 2010 11:27:47 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[down-casting]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[polymorphism]]></category>
		<category><![CDATA[up-casting]]></category>
		<category><![CDATA[객체지향 프로그래밍]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[다운캐스팅]]></category>
		<category><![CDATA[다형성]]></category>
		<category><![CDATA[방법론]]></category>
		<category><![CDATA[상속]]></category>
		<category><![CDATA[업캐스팅]]></category>
		<category><![CDATA[캐스팅]]></category>
		<category><![CDATA[클래스]]></category>
		<category><![CDATA[형변환]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=539</guid>
		<description><![CDATA[이 포스트는 &#8220;여러분은 플래시로 언제까지 네비게이션 바나 만들고 있을껀가요?&#8221; 로부터 이어진 내용입니다. 날코딩을 탈피해 보자는 첫걸음 중 한 발자국인 OOP(Object-Oriented Programming)의 다형성(Polymorphism)에 대해 알아보는 시간입니다. A. Polymorphism in ActionScript (액션스크립트에서의 다형성) 그럼 액션스크립트에서는 다형성이 어떻게 나타나는 걸까요? 먼저 위키백과 한글판의 OOP 항목에 나타난 다형성에 대한 설명을 인용해 보겠습니다. 다형성이란 같은 메시지에 대해 클래스에 따라 다른 [...]]]></description>
			<content:encoded><![CDATA[<p>이 포스트는 &#8220;<a href="http://ufx.kr/blog/510">여러분은 플래시로 언제까지 네비게이션 바나 만들고 있을껀가요?</a>&#8221; 로부터 이어진 내용입니다. 날코딩을 탈피해 보자는 첫걸음 중 한 발자국인 OOP(Object-Oriented Programming)의 다형성(Polymorphism)에 대해 알아보는 시간입니다.</p>
<h3>A. Polymorphism in ActionScript (액션스크립트에서의 다형성)</h3>
<p>그럼 액션스크립트에서는 다형성이 어떻게 나타나는 걸까요?<br />
먼저 <a href="http://ko.wikipedia.org/wiki/OOP" target="_blank">위키백과 한글판의 OOP 항목</a>에 나타난 다형성에 대한 설명을 인용해 보겠습니다.</p>
<blockquote><p>다형성이란 같은 메시지에 대해 클래스에 따라 다른 행위를 하게 되는 특징이다. 일반적으로 같은 이름을  가지는 메서드에 대해 인자(Argument)의 개수와 데이터형(Data Type)에 따라 수행되는 행위가 달라짐을 의미한다.  다형성을 통해서 사용자는 약속된 인터페이스를 따르는 서로 다른 객체를 같은 방식으로 사용 할 수 있게 된다.</p></blockquote>
<p>상당한 숫자의 플래시 개발자들이 해당되겠습니다만, 여러분이 액션스크립트 이전에 다뤄본 객체지향 언어가 없다면 위의  설명만으로는 다형성이 도무지 무엇인지 이해할 수가 없을 것입니다. 특히나 액션스크립트같이 다뤄지는 객체 대부분이 시각적인 표현을  다루는 경우라면, 다형성이라는 개념은 &#8220;단지 여러가지 형태를 가지고 있는 그 어떤것&#8221; 정도의 피상적인 개념만 느끼게 되는거죠.</p>
<p><span id="more-539"></span></p>
<blockquote><p>&#8220;MovieClip 으로 만든 객체가 여러가지 형태(디자인)을 가지고 있는게 다형성인가?&#8221;</p></blockquote>
<p>또는,</p>
<blockquote><p>&#8220;라이브러리 패널에 MyButton 이라고 클래스 이름 정의된 자원이 있다면 var button1:MyButton = new  MyButton( &#8220;blue&#8221; ); 할때도 있고, var button2:MyButton = new MyButton( &#8220;red&#8221; )  할수도 있는 등, 형태 또는 색상을 바꿔서 사용하는게 다형성 일걸?&#8221;</p></blockquote>
<p>이것도 아니면,</p>
<blockquote><p>&#8220;하나의 상위 클래스를 상속한 하위 클래스가 여러 가지 type 인 상황이 다형성이겠지?&#8221;</p></blockquote>
<p>네이티브 개발자들이 보면 한참 웃다 잃어버린 배꼽을 찾으러 돌아다닐 것 같은 이런 생각들을 초보 플래시 개발자들이 실제로 하고 있습니다.</p>
<p>그러나 액션스크립트의 다형성이라고 다른 언어의 다형성과 다르지 않습니다.</p>
<p><img class="alignleft" title="polimorphism_letter" src="http://ufx.kr/blog/wp-content/uploads/2010/10/polimorphism_letter.png" alt="polimorphism" width="300" height="183" />다형성(多形性)의 한자에서 가운데 &#8220;형(形)&#8221;은 프로그래밍 적인 관점으로 해석했을때 type 입니다. 즉, 하나의 객체가 여러가지  type 을 가질 수 있다는 의미 입니다. 객체지향 프로그래밍에서 type 이란 무엇인가요? 바로 Class 이름이죠. var  button:MyButton 과 같이 변수를 생성 했을때 MyButton 이 바로 Class 이름임과 동시에 button 객체의  type 입니다. 결국, &#8220;객체가 여러 가지 Class 형태를 가지게 된다.&#8221; 라고 다형성을 바꿔서 설명할 수 있습니다.</p>
<p>언뜻 이해가 안될 수도 있습니다. 아니, 어쩌면 초보 플래시 개발자는 이해가 되지 않는게 당연한 것일테니 실망할 필요는 없습니다.</p>
<p>그럼 이 부분을 설명하기 위해 객체지향 프로그래밍에서 하나의 객체를 생성하면 컴퓨터는 어떻게 이 객체를 생성하며 인식하게  되는지 알아야 할 필요가 있습니다. 이 부분을 이해하게 되면 어째서 다형성이 구현될 수 있는지 논리적 근거를 이해하게 됩니다.</p>
<p>컴퓨터, 그러니까 우리는 이것을 컴파일러라고 볼 수도 있고 플래시 플레이어라고 볼 수도 있습니다. 어떻게 생겨먹은 녀석이건  간에 우리가 var button:MyButton = new MyButton() 이라고 코딩했을때 이 녀석은 상속 체인상의 모든  부모 객체를 만들어 냅니다. 여러분은 그런거 본적이 없다고 해도 사실이 그렇습니다.</p>
<p>우리는 코드로 설명하면 이해가 빨리 되죠?<br />
MyButton.as 파일에는 아래와 같이 코딩 되어 있을겁니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MyButton extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> MyButton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 관련 코드들</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위의 클래스 정의를 보면 MyButton 클래스는 Sprite 를 상속(확장) 했음을 알 수 있습니다.<br />
이 클래스를 호스트 코드에서 var button:MyButton = new MyButton(); 하는 순간 컴파일러는  MyButton 객체와 Sprite 객체와 DisplayObjectContainer 객체와 InteractiveObject 객체와  DisplayObject 객체와 EventDispatcher 객체와 최상위의 Object 객체까지, MyButton 의 상속  체인상 모든 type 의 객체를 실제 만들어서 메모리상에 기록합니다.</p>
<div id="attachment_523" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-523 " title="Inheritance_chain" src="http://ufx.kr/blog/wp-content/uploads/2010/10/Inheritance_chain.png" alt="" width="590" height="446" /><p class="wp-caption-text">var button:MyButton = new MyButton(); 을 하게 되면 상속 체인상의 모든 객체들이 생성됩니다. 다만 받아내는 변수에 따라 가리키는 대상이 다를뿐!!</p></div>
<p>그리고 위와같이 호스트 코드에서 new MyButton() 를 하고 var button:MyButton 에 대입하게 되면, 생성된 총  7개의 객체중 한 가지 type 인 MyButton type의 객체만 실제로 사용하게 됩니다. 대단한 낭비라고 생각하실지  모르겠습니다만, 실제로 컴파일러나 플래시 플레이어는 이렇게 작동합니다. 그런데 다형성이 구현되는 논리적인 근거가 여기에 있습니다.  그 근거가 무엇인지는 잠시 후에 살펴 보기로 하고,</p>
<p>아래의 호스트 코드를 보실까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// MyButton 형으로 생성하고 MyButton 형의 변수에 대입함</span>
<span style="color: #6699cc; font-weight: bold;">var</span> button<span style="color: #000000; font-weight: bold;">:</span>MyButton = <span style="color: #0033ff; font-weight: bold;">new</span> MyButton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// MyButton 형으로 생성했지만 Sprite 형의 변수에 대입함</span>
<span style="color: #6699cc; font-weight: bold;">var</span> button<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> MyButton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>위의 코드는 둘다 유효한 코드 입니다. 전자의 경우는 생성과 변수를 같은 type 으로 한 경우이고, 후자의 경우는  하위클래스로 생성하고 상위 클래스의 변수로 받은 상황 입니다. 후자의 경우에는 암시적 형 변환이 일어났다고 표현하죠. 즉, 아래와  같은 코드를 한 줄로 표현한거라 할 수 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> button<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span>; <span style="color: #009900;">// Sprite 형의 변수 선언</span>
<span style="color: #6699cc; font-weight: bold;">var</span> myButton<span style="color: #000000; font-weight: bold;">:</span>MyButton = <span style="color: #0033ff; font-weight: bold;">new</span> MyButton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// MyButton 형의 객체 생성</span>
button = myButton; <span style="color: #009900;">// 상위 형의 변수에 하위 형의 객체를 대입. 암시적 형 변환이 일어남</span></pre></td></tr></table></div>

<p>형 변환(casting: 캐스팅)이란 단어는 초보 개발자라 할 지라도 어떤 것인지 익히 알고들 계실 겁니다. 위와 같이  관련된 다른 type 으로 변형 하는 것을 형 변환 이라고 하는 거죠. 관련이 없는 type 끼리는 형 변환이 실패하게 됩니다. 형  변환은 기본적으로 상속 체인상의 상하위 클래스간의 형 변환만이 가능합니다. (아래쪽, 형 변환의 제한 참고)</p>
<p>형 변환에 대해 좀더 알아보고 넘어가겠습니다. 이 포스트에서는 &#8220;형 변환&#8221;이라는 우리말 표현과 &#8220;캐스팅&#8221;이라는 영어식 표현을 혼용해서 사용하고 있습니다만, 이해를 돕기 위해 사용한 것일뿐, 완전히 동일한 것을 가리키는 표현입니다.</p>
<p>하위 type에서 상위 type으로 형 변환 하는 것을 up-casting (업 캐스팅) 이라고 하고, 그 반대의 경우를  down-casting (다운 캐스팅) 이라고 합니다.  업 캐스팅은 위의 호스트 코드에서 본 것과 같이 암시적 형 변환이  가능하지만 다운 캐스팅은 명시적 형 변환만 가능합니다. 이 내용은 아래에서 다시 자세히 살펴보겠습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> button<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> MyButton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> myButton<span style="color: #000000; font-weight: bold;">:</span>MyButton;
myButton = button <span style="color: #0033ff; font-weight: bold;">as</span> MyButton; <span style="color: #009900;">// as 연산자로 캐스팅 할 수도 있고 myButton = MyButton( button ) 과 같이 캐스팅 할 수도 있음</span></pre></td></tr></table></div>

<p>위에서 new MyButton() 하게 되면 총 7개의 객체를 메모리에 생성한다고 했죠? 형 변환이 일어나게 되면 변수가 가리키는 대상이 형 변환이 일어난 type 을 가리키게 됩니다.</p>
<p>이렇게 다형성이라는 것은 그것이 암시적이든 명시적이든 형 변환과 관계를 가지고 있습니다. 위에서 형 변환은 상속 체인에서만 일어날 수 있다고 설명하였으므로 다형성은 것은 결국 상속과 밀접한 관계를 가지게 됩니다.</p>
<h4>1. down-casting</h4>
<p>그러면 이렇게 형 변환을 해서 얻는 이득이 무엇인 걸까요?<br />
초보 개발자에게 있어 형 변환을 해본 경험은 대략,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #004993;">MovieClip</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">parent</span> <span style="color: #000000;">&#41;</span>.<span style="color: #004993;">gotoAndStop</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">2</span> <span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>위와 같은 일을 수행하기 위해서 일 것입니다. 그런데 parent 라는 속성은 DisplayObject 클래스에서 정의된 읽기 전용 속성이고 DisplayObjectContainer 를 반환하기 때문에<sup>[<a href="http://ufx.kr/blog/539#footnote_0_539" id="identifier_0_539" class="footnote-link footnote-identifier-link" title="http://help.adobe.com/ko_KR/Flash/CS5/AS3LR/flash/display/DisplayObject.html#parent">01</a>]</sup>  그보다 두 단계 하위 단계에 있는 MovieClip 형의 메서드인 gotoAndStop() 메서드를 사용할 수가 없으므로, <sup>[<a href="http://ufx.kr/blog/539#footnote_1_539" id="identifier_1_539" class="footnote-link footnote-identifier-link" title="즉, this.parent 는 DisplayObjectContainer 형 이므로 gotoAndStop() 메서드가 존재하지  않는다는 의미.">02</a>]</sup> gotoAndStop() 메서드를 사용할 수 있도록 MovieClip( 캐스팅대상 ) 으로 형 변환 해 준다는  의미 이므로 이것은 다운 캐스팅에 해당합니다.</p>
<p>결국, 다운 캐스팅을 하는 이유는 이와 같이 상위 형의 클래스에는 정의 되어 있지 않은 메서드나 속성을 사용하기 위해 그것을 사용할 수 있는 형으로 변환 하기 위함입니다.</p>
<h4>2. up-casting</h4>
<p>그렇다면 업 캐스팅은 어떤 경우에 사용할까요? 언뜻 보기에 업 캐스팅으로 얻어지는 이득이 없을 것 같아 보일 수도 있을  것입니다. 상위 형의 클래스에는 하위 형의 클래스보다 할 수 있는 일이 적거나 같기 때문에 드는 생각이죠. 그러나 만약 형 변환이  다운 캐스팅만 존재한다면 형 변환은 거의 무의미한 행위가 됩니다. 무엇보다도 gotoAndStop() 메서드 따위를 쓰자고 형  변환 씩이나 하는건 귀찮습니다. AS2.0 에서 MovieClip 클래스가 바로 Object 클래스를 상속 받아버렸듯 그냥 상위  클래스에 모든 기능을 다 때려박으면 캐스팅이고 뭐고 할 필요가 없겠죠.</p>
<p>예컨대 아래와 같은 상위 클래스가 있고,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> SuperClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;SuperClass created.&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> superClassMethod<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;DoSomething in SuperClass !!&quot;</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위의 상위 클래스를 상속한 하위 클래스가 아래와 같이 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SubClass extends SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;SubClass created.&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;DoSomething in SubClass !!&quot;</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위와 같은 상속 구조와 메서드의 경우에서는 형 변환으로 얻는 이득이 없습니다.<br />
호스트 코드는 어떤 상황인지 볼까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> obj<span style="color: #000000; font-weight: bold;">:</span>SuperClass = <span style="color: #0033ff; font-weight: bold;">new</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 이렇게 up-casting 을 했다면</span>
obj.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 컴파일 에러!!</span></pre></td></tr></table></div>

<p>당연한 결과죠? obj 변수는 SuperClass 형이기 때문에 doSomething() 메서드가 존재하지 않습니다.<br />
그렇다면,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> obj<span style="color: #000000; font-weight: bold;">:</span>SuperClass = <span style="color: #0033ff; font-weight: bold;">new</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
obj.superClassMethod<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 이것은 당연히 가능</span>
SubClass<span style="color: #000000;">&#40;</span> obj <span style="color: #000000;">&#41;</span>.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 다운 캐스팅을 수행했기 때문에 이것도 가능함</span></pre></td></tr></table></div>

<p>위와같이 사용해야 합니다.</p>
<p>&#8220;에&#8230; 이거 뭔가요? 아주 불편하잖아요. 다형성 뭐하러 구현하나요?&#8221; 하는 웅성거림이 들려오는듯 합니다.</p>
<p>맞습니다. 단순히 형 변환만 해서는 다형성으로 인한 이득을 얻을 수 없습니다. 때문에 여기에서 중요한 키워드가 등장해야 하는데, 바로 override 입니다.</p>
<h4>3. override</h4>
<p>override 키워드는 상위 클래스에서 정의한 메서드를 하위 클래스에서 재정의 할때 사용합니다. 위의 두 개의 클래스  구조는 예제속에서만 존재하는 아주 간단한 상속 구조라고 할 수 있습니다. 그러나 실제로 프로젝트에서는 어떤가요? 1개의 상위  클래스에는 2개 이상, 무한대 수의 하위 클래스가 상속할 수 있습니다. 게임 설계에서 몬스터를 구현하는 내용을 예로 들어볼까요?</p>
<p>몬스터들은 hp 가 있고, 이리저리 로밍(roaming) 하다가, 플레이어를 발견하면 attack 하기도 하고, 플레이어에게  얻어맞으면 피해(damage)를 받게 됩니다. 또한 몬스터의 종류마다 제각각 공격력이 다를 것이므로 공격등급(rating)  속성을 가질 것이고, hp 가 일정 수준 이하로 떨어지면 도망(runAway)칠 수도 있죠.<br />
이 내용을 가지고 Monster.as 클래스를 만들어 볼까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Monster extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _hp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">100</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _runAwayHp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">10</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _rating<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">20</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Monster<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;---몬스터 생성 공통 초기화---&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span> $target<span style="color: #000000; font-weight: bold;">:</span>Player <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 플레이어 객체에 _rating 만큼의 데미지를 가함</span>
			$target.damage = _rating;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #0033ff; font-weight: bold;">set</span> damage<span style="color: #000000;">&#40;</span> $damage<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>._hp <span style="color: #000000; font-weight: bold;">-</span>= $damage;
&nbsp;
			<span style="color: #009900;">// 데이지를 받은 후 _hp 가 _runAwayHp 미만으로 떨어지면 runAway() 메서드 실행</span>
			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>._hp <span style="color: #000000; font-weight: bold;">&lt;</span>= <span style="color: #000000; font-weight:bold;">0</span> <span style="color: #000000;">&#41;</span>
				die<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">else</span> <span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>._hp <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #0033ff; font-weight: bold;">this</span>._runAwayHp <span style="color: #000000;">&#41;</span>
				runAway<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> runAway<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">throw</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Error</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;override runAway() method !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> roaming<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 어슬렁 거리는 알고리즘 구현</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> die<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;몬스터 사망&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Monster 클래스는 아래에 나올 여러 가지 몬스터들의 공통적인 부분을 끌어올린 일종의 추상층 이라고 할 수 있습니다.  Monster 클래스에서는 변수나 메서드의 접근 제한자가 public 인지, protected 인지 주의해서 살펴보세요.</p>
<p>다음은 Monster 클래스를 상속한 Gobblin 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Goblin extends Monster
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Goblin<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;Goblin&quot;</span>;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;생성&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._hp = <span style="color: #000000; font-weight:bold;">70</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._runAwayHp = <span style="color: #000000; font-weight:bold;">10</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._rating = <span style="color: #000000; font-weight:bold;">15</span>;
			roaming<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> runAway<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Goblin 의 ㅌㅌㅌ 알고리즘 구현</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>생성자에서 기본 스탯을 세팅했고, runAway() 메서드를 override 하여 Gobblin 만의 도망가는 알고리즘을 구현하면 되겠습니다.</p>
<p>다음은 Dragon 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Dragon extends Monster
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _fireRating<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">100</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Dragon<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;Dragon&quot;</span>;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;생성&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._hp = <span style="color: #000000; font-weight:bold;">200</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._runAwayHp = <span style="color: #000000; font-weight:bold;">0</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._rating = <span style="color: #000000; font-weight:bold;">50</span>;
			roaming<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span> $target<span style="color: #000000; font-weight: bold;">:</span>Player <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Dragon Monster는 기본 공격력(_rating)에 화염데미지(_fireRating)를 추가함</span>
			$target.damage = _rating <span style="color: #000000; font-weight: bold;">+</span> _fireRating;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> runAway<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Dragon 은 도망가지 않음</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Dragon 몬스터는 기본 데미지에 화염 데미지를 더해서 총 데미지를 계산 하는군요. Monster 클래스의 기본 공격 계산과 다르기 때문에 attack() 메서드를 override 했습니다.</p>
<p>그리고 Troll 클래스는 다음과 같습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Troll extends Monster
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _poisonRating<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">30</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Troll<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;Troll&quot;</span>;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;생성&quot;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._hp = <span style="color: #000000; font-weight:bold;">120</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._runAwayHp = <span style="color: #000000; font-weight:bold;">12</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>._rating = <span style="color: #000000; font-weight:bold;">20</span>;
			roaming<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span> $target<span style="color: #000000; font-weight: bold;">:</span>Player <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Troll Monster는 기본 공격력(_rating)에 독데미지(_poisonRating)를 추가함</span>
			$target.damage = _rating;
			$target.dotDamage = _poisonRating;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> runAway<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Troll 의 ㅌㅌㅌ 알고리즘 구현</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Troll 몬스터는 기본 데미지에 추가로 독 데미지를 주게 되는데  기본 데미지에 합산 하는 방식이 아니라 틱(tick)당 데미지를 주는 방식입니다.</p>
<p>위에서 보시는 바와 같이 각 몬스터 종류 마다 attack() 하여 데미지를 주는 방식이 다르므로, 데미지를 계산하고 _hp  를 깍아내는 코드는 Monster 클래스가 아닌 각각의 하위 클래스에 위치해야 합니다. 물론 Goblin클래스처럼  attack() 메서드를 override 하지 않으면 Monster 클래스에 있는 attack() 메서드의 계산이 실행 되면서  기본 데미지 만을 주게 되겠죠. runAway() 메서드도 마찬가지로 몬스터 별로 구현하는 방식이 다릅니다. 단,  runAway() 메서드는 new Error() 를 던져줌으로서 하위 클래스에서 반드시 구현하게끔 하고 있습니다. 즉,  runAway() 메서드는 Monster 클래스를 상속한 하위 클래스라면 반드시 override 해야 합니다.</p>
<p>이런 상속 구조를 가진 monster package 되겠습니다. 이 클래스들을 UML로 표현하면 다음과 같습니다.<br />
<img class="aligncenter" title="monster_Inheritance" src="http://ufx.kr/blog/wp-content/uploads/2010/10/monster_Inheritance.png" alt="" width="402" height="364" /></p>
<p>한결 정리가 되죠?<br />
그리고 이 몬스터들과 대적하는 Player 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.utils</span>.<span style="color: #004993;">Timer</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">TimerEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Player extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _hp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">200</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _rating<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">30</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _tick<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Timer</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Timer</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">1000</span>, <span style="color: #000000; font-weight:bold;">5</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _totalDotDamage<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">0</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Player<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;---플레이어 생성---&quot;</span> <span style="color: #000000;">&#41;</span>;
			_tick.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">TimerEvent</span>.<span style="color: #004993;">TIMER</span>, onTick <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span> $target<span style="color: #000000; font-weight: bold;">:</span>Monster <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 몬스터 객체에 _rating 만큼의 데미지를 가함</span>
			$target.damage = _rating;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #0033ff; font-weight: bold;">set</span> damage<span style="color: #000000;">&#40;</span> $damage<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			_hp <span style="color: #000000; font-weight: bold;">-</span>= $damage;
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;플레이어 캐릭터 hp :&quot;</span>, _hp <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> _hp <span style="color: #000000; font-weight: bold;">&lt;</span>= <span style="color: #000000; font-weight:bold;">0</span> <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;플레이어 캐릭터 사망&quot;</span> <span style="color: #000000;">&#41;</span>;
				_tick.<span style="color: #004993;">stop</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #0033ff; font-weight: bold;">set</span> dotDamage<span style="color: #000000;">&#40;</span> $damage<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// Timer 를 이용해 시간당 데미지를 받는 알고리즘 구현</span>
			_totalDotDamage <span style="color: #000000; font-weight: bold;">+</span>= $damage;
			_tick.<span style="color: #004993;">reset</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			_tick.<span style="color: #004993;">start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> onTick<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">TimerEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			damage = <span style="color: #004993;">Math</span>.<span style="color: #004993;">round</span><span style="color: #000000;">&#40;</span> _totalDotDamage <span style="color: #000000; font-weight: bold;">/</span> <span style="color: #000000; font-weight:bold;">10</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Monster 클래스와 Player 클래스는 공통된 부분이 제법 보이는군요. 그렇다면 나중에 리팩토링을 통해서  Charactor 클래스로 공통된 부분을 올리고 상속을 하면 되겠군요. 그러나 이 포스트는 리팩토링에 관한 포스트가 아니므로 이  부분에 대한 공부는 다음기회로 넘기고&#8230;</p>
<p>그럼 이 몬스터들과 플레이어를 호스트 코드에서 돌려 볼까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MonsterTestDrive extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> MonsterTestDrive<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> player<span style="color: #000000; font-weight: bold;">:</span>Player = <span style="color: #0033ff; font-weight: bold;">new</span> Player;
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> monsterList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span> <span style="color: #0033ff; font-weight: bold;">new</span> Gobblin, <span style="color: #0033ff; font-weight: bold;">new</span> Dragon, <span style="color: #0033ff; font-weight: bold;">new</span> Troll <span style="color: #000000;">&#93;</span>;
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> mob<span style="color: #000000; font-weight: bold;">:</span>Monster;
			<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> mob <span style="color: #0033ff; font-weight: bold;">in</span> monsterList <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> mob.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;몬스터가 플레이어를 공격 합니다.&quot;</span> <span style="color: #000000;">&#41;</span>
				mob.attack<span style="color: #000000;">&#40;</span> player <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>출력 내용은&#8230;</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">---</span>플레이어 생성<span style="color: #000000; font-weight: bold;">---</span>
<span style="color: #000000; font-weight: bold;">---</span>몬스터 생성 공통 초기화<span style="color: #000000; font-weight: bold;">---</span>
Goblin 생성
어슬렁 어슬렁
<span style="color: #000000; font-weight: bold;">---</span>몬스터 생성 공통 초기화<span style="color: #000000; font-weight: bold;">---</span>
Dragon 생성
어슬렁 어슬렁
<span style="color: #000000; font-weight: bold;">---</span>몬스터 생성 공통 초기화<span style="color: #000000; font-weight: bold;">---</span>
Troll 생성
어슬렁 어슬렁
Goblin 이 플레이어를 공격 합니다.
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">185</span>
Dragon 이 플레이어를 공격 합니다.
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">35</span>
Troll 이 플레이어를 공격 합니다.
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">15</span>
플레이어가 tick 당 데미지를 받고 있음<span style="color: #000000; font-weight: bold;">----</span>
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">12</span>
플레이어가 tick 당 데미지를 받고 있음<span style="color: #000000; font-weight: bold;">----</span>
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">9</span>
플레이어가 tick 당 데미지를 받고 있음<span style="color: #000000; font-weight: bold;">----</span>
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">6</span>
플레이어가 tick 당 데미지를 받고 있음<span style="color: #000000; font-weight: bold;">----</span>
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">3</span>
플레이어가 tick 당 데미지를 받고 있음<span style="color: #000000; font-weight: bold;">----</span>
플레이어 캐릭터 hp <span style="color: #000000; font-weight: bold;">:</span> <span style="color: #000000; font-weight:bold;">0</span>
플레이어 캐릭터 사망</pre></td></tr></table></div>

<p>몬스터들이 인정사정 없군요. 플레이어는 체력이 0 이 되서 결국 사망했습니다.<br />
플레이어는 몬스터들의 attack() 메서드로 인해 데미지를 받았는데, 호스트 코드에서 순환문으로 돌릴 수 있었습니다. 이렇게 할  수 있는 것은 모든 몬스터들에게 attack() 메서드가 public 으로 존재하기 때문이죠. 그런데 Goblin,  Dragon, Troll 클래스에 attack() 메서드가 존재하고 있다는 확신을 할 수 있는 것은 이 세 개의 클래스들이  Monster 클래스를 상속했기 때문 입니다.</p>
<p>자 그럼, 위의 호스트 코드의 순환문 for each( mob in monsterList ) 의 바로 위에 있는 var  mob:Monster 에 주목하세요. monsterList 배열에 있는 각각의 원소들은 모두 데이터 형이 다릅니다. 클래스가  다르죠. 그런데 이 배열 원소를 순환할 때는 이 배열원소보다 상위 클래스인 Monster 클래스로 받고 있습니다.<sup>[<a href="http://ufx.kr/blog/539#footnote_2_539" id="identifier_2_539" class="footnote-link footnote-identifier-link" title="암시적 업  캐스팅이 적용 된것입니다.">03</a>]</sup> Monster 에도 기본형으로 attack() 메서드가 존재하므로 Goblin 과 같이 별도로  attack() 메서드를 override 하지 않았다면 Monster 클래스의 attack() 메서드가 호출되고, Dragon  이나 Troll 과 같이 별도의 데미지와 공격방식을 가진 다른 몬스터들은 override 된 attack() 메서드가 호출 되는  것입니다.</p>
<p>편리하죠? 우리는 순환문을 돌릴때 배열에 들어가 있는 몬스터들의 여러 가지 type에는 신경쓰지 않아도 됩니다. 만약 위와  같이 업캐스팅을 이용한 다형성을 적용하지 않으면 Goblin, Dragon, Troll용 순환문을 각각 돌려야 할 가능성이  높습니다. 또는 var mob:* 과 같이 형을 지정하지 않은 변수로 받아야 할텐데, 이렇게 되면 코드 힌트를 받지 못하는 것은  둘째 치고, attack() 메서드가 존재하는지 확신할 수 없으므로 순환문의 신뢰도가 떨어질 수 밖에 없습니다. 여러분이 만든  게임의 몬스터의 종류가 세 가지만 있을 것 같진 않죠? 이렇게 다형성을 이용하면 코드가 견고해지고 유지보수하기 편해집니다.</p>
<p>이렇게 다형성은 상속을 기본으로, 그중에서도 override 와 특히 깊은 관계를 가집니다.</p>
<h4>4. parameter</h4>
<p>한편, 메서드의 인자(파라미터)에 대해서도 다형성을 적용해 볼 수 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">KeyboardEvent</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> HandlerExample extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> HandlerExample<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">stage</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, run <span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">stage</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">KeyboardEvent</span>.<span style="color: #004993;">KEY_DOWN</span>, run <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> run<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Event</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> $e <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>stage 에 걸려 있는 두 가지 다른 종류의 이벤트 핸들러를 하나의 이벤트 핸들러로 처리하고 있습니다. 이것이 가능한  이유는 MouseEvent 나 KeyboardEvent 모두 Event 를 상속한 하위 클래스이기 때문 입니다. 역시 위의 경우도  이벤트 리스너에서 보낸 이벤트 객체를 이벤트 핸들러가 인자로 받으면서 암시적 업 캐스팅이 적용되었습니다.</p>
<h4>5. interface</h4>
<p>지금까지는 상속(inheritance) 체인상에서의 다형성을 알아봤는데요, 인터페이스 키워드(interface)로도 다형성을  구현할 수 있습니다. 인터페이스를 &#8220;구현상속&#8221;이라고 부르기도 하는데, 다형성 측면에서도 여러 모로 상속과 비슷해 보이기  때문이죠.</p>
<p>아래는 Monster 클래스에 붙일 IAttack 인터페이스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> interface IAttack
	<span style="color: #000000;">&#123;</span>
		<span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span> $target<span style="color: #000000; font-weight: bold;">:</span>Player <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>몬스터용 이기 때문에 $target 인자를 Player 형으로 받고 있습니다.<br />
그러면 Monster 클래스는 어떻게 수정하면 될까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Monster implements IAttack <span style="color: #009900;">// IAttack 인터페이스를 구현</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #009900;">// Monster 클래스의 다른 부분은 기존 코드와 동일 ...</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>네. 간단하죠. Monster 클래스에는 이미 attack() 메서드가 존재하므로 IAttack 인터페이스는 곧바로 구현된  것입니다. 바뀌는 코드는 고작 여기까지 입니다. 상황에 따라 개별 Goblin, Dragon, Troll 클래스에 각각  IAttack 인터페이스를 붙여도 마찬가지로 동작합니다.</p>
<p>그럼 호스트 코드에서는 어떻게 사용하게 될까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> InterfaceTestDrive extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> InterfaceTestDrive<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> player<span style="color: #000000; font-weight: bold;">:</span>Player = <span style="color: #0033ff; font-weight: bold;">new</span> Player;
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> monsterList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span> <span style="color: #0033ff; font-weight: bold;">new</span> Goblin, <span style="color: #0033ff; font-weight: bold;">new</span> Dragon, <span style="color: #0033ff; font-weight: bold;">new</span> Troll <span style="color: #000000;">&#93;</span>;
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> mob<span style="color: #000000; font-weight: bold;">:</span>IAttack; <span style="color: #009900;">// mob 을 IAttack 형으로 받고 있음</span>
			<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> mob <span style="color: #0033ff; font-weight: bold;">in</span> monsterList <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> Monster<span style="color: #000000;">&#40;</span> mob <span style="color: #000000;">&#41;</span>.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;이 플레이어를 공격 합니다.&quot;</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// Monster 클래스의 속성을 이용하고 싶다면 형 변환!!</span>
				mob.attack<span style="color: #000000;">&#40;</span> player <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>어떻습니까? 매우 편리하죠? 호스트코드에서는 배열에 들어있는 몬스터가 어떤 종류건 간에 관계 없이(알 필요 없이) IAttack 인터페이스를 구현하기만 했다면 순환문을 돌릴 수 있게 됩니다. 다형성을 이용해서 말이죠.</p>
<h3>B. How to apply  (적용 방법)</h3>
<p>그런데 이런 방식으로 형 변환을 이용한 다형성의 이득을 챙기려면 몇 가지 규칙을 알고 있어야 합니다. 다르게 말하자면 아래에 나열할 규칙들은 객체지향 프로그래밍에서 상속을 구현할 때 알아야 되는 규칙들이기도 합니다.</p>
<h4>1. 하위 형으로 생성하고 상위 형 변수로 받는다.</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span>SuperClass = <span style="color: #0033ff; font-weight: bold;">new</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>위의 Monster 추상 클래스와 하위 개별 구상 클래스들과 같이 상속 구조가 잘 구성되어 있다면 모든 행동을 상위 클래스 형  만으로 할 수 있게 됩니다. 즉, 개별 구상 클래스는 추상클래스에서 구현하도록 한 public 메서드 외에는 자신만 가진  public 메서드는 없는 것이 좋겠죠. 이렇게 추상층과 구상층이 잘 구성되면 Monster 형의 변수만 가지고도 모든 몬스터들의  행동을 표현할 수 있게 됩니다.</p>
<h4>2. 상속 체인상의 상하위 클래스간에만 형 변환 가능.</h4>
<p><img class="alignleft" title="Inheritance_chain_only" src="http://ufx.kr/blog/wp-content/uploads/2010/10/Inheritance_chain_only.png" alt="Inheritance chain only" width="400" height="263" />A 클래스를 상속한 B 클래스와 C 클래스가 있을 경우 A 형태와 B 형태는 캐스팅이 가능하고, A 형태와 C 형태는  캐스팅이 가능하지만, B 형태와 C 형태간 형 변환을 시도하면 플래시 플레이어가 에러를 뿜어줍니다.</p>
<p>객체지향 프로그래밍에서  부모자식은 있어도 형제 자매라는 개념은 존재하지 않습니다. 게다가 애초에 상속 체인을 부모자식 관계로 이해하는것 자체가 에러입니다.<sup>[<a href="http://ufx.kr/blog/539#footnote_3_539" id="identifier_3_539" class="footnote-link footnote-identifier-link" title="AS3.0 클래스의 상속(extends)구조에서 상위, 하위 클래스의 메서드 호출방법 의 가장 첫 문단 참고">04</a>]</sup><br />
같은 상위 클래스를 상속한 하위 클래스는 서로 관계가 없는 클래스이고 그 type 끼리는 형 변환이 실패하게 됩니다. 형 변환은 기본적으로 상속 체인상의 상하위 클래스간의 형 변환만이 가능하다는 것을 기억하세요.</p>
<h4>3. up-casting 은 implicit casting (암시적 형 변환) 가능.</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> object1<span style="color: #000000; font-weight: bold;">:</span>SuperClass; <span style="color: #009900;">// 상위 형으로는 변수만 선언</span>
<span style="color: #6699cc; font-weight: bold;">var</span> object2<span style="color: #000000; font-weight: bold;">:</span>SubClass = <span style="color: #0033ff; font-weight: bold;">new</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 하위 형으로는 객체까지 생성</span>
object1 = object2; <span style="color: #009900;">// 하위형의 객체를 상위형의 변수에 대입(암시적 형 변환)</span></pre></td></tr></table></div>

<p>상위 클래스는 서브클래스에 비해 메서드와 속성의 갯수가 같거나 적기 때문에, 다르게 표현하면 기능이 적은 클래스로 형 변환  하는 것이기 때문에 형 변환 검사를 느슨하게 해도 되고, 따라서 암시적 형 변환이 가능합니다. 변수가 상위 형이고 값이 하위 형인  경우에는 캐스팅을 하지 않아도 대입하는 과정에서 자동으로 형 변환이 일어 납니다.</p>
<h4>4. down-casting 은 explicit casting (명시적 형 변환)만 가능.</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> object<span style="color: #000000; font-weight: bold;">:</span>SuperClass = <span style="color: #0033ff; font-weight: bold;">new</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 상위형의 변수에 하위형의 객체 생성</span>
object.superClassMethod<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 상위형의 메서드 호출 가능</span>
SubClass<span style="color: #000000;">&#40;</span> object <span style="color: #000000;">&#41;</span>.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 명시적 형 변환을 해야만 하위 형의 메서드 호출 가능</span></pre></td></tr></table></div>

<p>up-casting 과는 반대로 이 경우에는 메서드와 속성의 숫자가 같거나 적은 상위 클래스에서 많은 쪽인 하위 클래스로 형  변환 해야 하기 때문에 형 변환이 유효한지 아닌지 검사를 하는 과정이 필요합니다. 그래서 다운캐스팅은 암시적 형 변환을 할 수  없고 명시적 형 변환만이 허용됩니다.</p>
<h4>5. 상위 형으로 생성하였다면 down-casting 불가.</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span>SuperClass = <span style="color: #0033ff; font-weight: bold;">new</span> SuperClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> temp<span style="color: #000000; font-weight: bold;">:</span>SubClass = SubClass<span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// Error !!!</span></pre></td></tr></table></div>

<p>위와 같은 경우 입니다. 상위 형으로 생성하고 상위 형의 변수로 받았다면, 그 상위형을 상속한 하위 클래스라 할지라도 다운  캐스팅을 할 수 없습니다. 어찌보면 당연하죠? var mc:Sprite = new Sprite(); 한 후, Monster( mc  ); 하는 것과 같으니까요. Sprite 객체를 아무리 캐스팅을 한들 Monster 객체가 될리 없습니다.</p>
<p style="text-align: center;">* * * * *</p>
<p>이렇게 다형성을 이용한 프로그래밍은 개발자에게 많은 이득을 가져다 줍니다. 코딩에 유연성을 부여하고 코딩을 담백하게 할 수 있도록 도와 줍니다. 게다가 상당항 분량의 코드를 줄일 수 있게 되면서, 코드가 명확해지고(가독성이 높아지고) 그로인해 유지보수가 수월해지게 되는거죠. 여러분도 이제 다형성을 이용한 코딩을 해 보세요. 형 변환 부터 시작하면 됩니다. ^^</p>
<ol class="footnotes"><li id="footnote_0_539" class="footnote"><a href="http://help.adobe.com/ko_KR/Flash/CS5/AS3LR/flash/display/DisplayObject.html#parent" target="_blank">http://help.adobe.com/ko_KR/Flash/CS5/AS3LR/flash/display/DisplayObject.html#parent</a></li><li id="footnote_1_539" class="footnote">즉, this.parent 는 DisplayObjectContainer 형 이므로 gotoAndStop() 메서드가 존재하지  않는다는 의미.</li><li id="footnote_2_539" class="footnote">암시적 업  캐스팅이 적용 된것입니다.</li><li id="footnote_3_539" class="footnote"><a href="../407">AS3.0 클래스의 상속(extends)구조에서 상위, 하위 클래스의 메서드 호출방법</a> 의 가장 첫 문단 참고</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/539/feed</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>여러분은 플래시로 언제까지 네비게이션 바나 만들고 있을건가요?</title>
		<link>http://ufx.kr/blog/510</link>
		<comments>http://ufx.kr/blog/510#comments</comments>
		<pubDate>Sat, 23 Oct 2010 11:28:11 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[객체지향 프로그래밍]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[다형성]]></category>
		<category><![CDATA[방법론]]></category>
		<category><![CDATA[상속]]></category>
		<category><![CDATA[은닉]]></category>
		<category><![CDATA[캡슐화]]></category>
		<category><![CDATA[클래스]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=510</guid>
		<description><![CDATA[액션스크립트는 클래스라던가, 인스턴스화를 할 수 있다던가, 메서드를 구성하고 호출할 수 있다던가 하는 요소들 덕분에 객체지향 프로그래밍을 할 수 있는 구조적 장치들을 충분히 가지고 있습니다. AS3.0 이 발표되고 시간이 흘러 현재에 와서는 개발자의 역량이 높아지고 유지보수의 편리성에 대한 열망이 점차 강해짐에 따라, 객체 지향적인 프로그래밍을 하려는 분위기가 조금씩 높아지고는 있습니다만, 실제 필드에 나가보면 정말로 객체지향 스럽게 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-541" title="oop_in_actionscript" src="http://ufx.kr/blog/wp-content/uploads/2010/10/oop_in_actionscript.png" alt="" width="300" height="132" />액션스크립트는 클래스라던가, 인스턴스화를 할 수 있다던가, 메서드를 구성하고 호출할 수 있다던가 하는 요소들 덕분에 객체지향 프로그래밍을 할 수 있는 구조적 장치들을 충분히 가지고 있습니다.<br />
AS3.0 이 발표되고 시간이 흘러 현재에 와서는 개발자의 역량이 높아지고 유지보수의 편리성에 대한 열망이 점차 강해짐에 따라, 객체 지향적인 프로그래밍을 하려는 분위기가 조금씩 높아지고는 있습니다만, 실제 필드에 나가보면 정말로 객체지향 스럽게 프로그래밍을 하는 경우는 보기가 드문 편이고, 날코딩으로 프로젝트를 수행하는 경우가 대부분임을 느낄 수 있습니다.</p>
<p>우리나라 경영진들의 개발에 대한 몰이해, 또는 액션스크립트 프로젝트는 프레임웍 이라기 보다는 front-end (사용자단) 쪽의 결과물로 표현되는 경우가 대부분이므로 JAVA 등과 같이 강한 객체지향 개발의 필요성을 느끼지 못하기 때문이기도 하는 이런저런 구조적인 문제점들이 있으나, 정작 가장 결정적인 이유는 액션스크립트 개발자 자신들의 역량 부족에 기인한다고 볼 수 있을 것입니다.<br />
즉, 액션스크립트 개발자들은 대부분 시각적인 것에 대단히 관심이 높은 (개발) 비전공자 출신인 경우가 많기 때문에, 화면만 어떻게 표현만 된다면 내부구조야 어찌되었든 별로 상관 없다는 식의 작업 방식을 취하는 경우가 많습니다. 이런 경우 프로젝트가 약간만 복잡해지거나 클라이언트의 유지보수 요구가 강하다면, 프로젝트 초반에 아무생각 없이 날코딩한 자신을 탓하고 있을 것이 틀림 없습니다.</p>
<p><span id="more-510"></span></p>
<div id="attachment_542" class="wp-caption alignright" style="width: 310px"><img class="size-full wp-image-542" title="debugging" src="http://ufx.kr/blog/wp-content/uploads/2010/10/debugging.jpg" alt="debugging" width="300" height="194" /><p class="wp-caption-text">여러분은 버그가 생길까봐 프로그램 수정을 두려워 하고 있진 않나요?</p></div>
<p>유지보수를 하고 수정을 하면 할 수록, 특히 자신이 초기 개발을 하지 않고 유지보수만을 담당하게 되었다면, 프로젝트의 전체 구조를 파악할 수 있는 시간도 주어지지 않고, 시간이 주어졌다고 해도 그런것에 쏟을 여력이 없는 우리 액션스크립트 개발자들은, 수정을 하면 할수록 버그가 생산된다는 것을 누구보다도 잘 알고 있습니다.</p>
<p>그래서 수정사항을 기피하거나, 수정의 분량이 조금만 많거나 새로운 기능이 들어가면 &#8220;이건 유지보수가 아니라 리뉴얼 해야됩니다. 그리고 (당연히) 비용이 많이 들어갑니다.&#8221; 라는 식으로 작업을 뒤로 미루거나 수정을 피할 수 없다면 재작업으로 유도하게 마련입니다. 이런 요구를 할 수 있는 상황이라면 그나마 나은 경우라고 할까요? 많은 경우 초기 개발이 어떻게 되었든간에 촉박한 기간내에 수정을 해 내야 합니다. 그러나 애초에 초기 개발부터 프로그램의 설계가 제대로 되었다면 간단히 수정이 가능한 일은 아니었을까요?</p>
<p>결국 이런 총제적인 난국이 작업 결과물의 부실을 낳고, 이런 부실이 액션스크립트 결과물들은 좋지 않다 라는 인식을 낳아, 또다시 그만그만한 front-end 작업물만을 담당하게 되는 악순환을 가져오게 됩니다.</p>
<h4>그럼 여러분은 플래시로 언제까지 네비게이션 바나 만들고 있을껀가요?</h4>
<p>객체지향 프로그래밍을 공부해야 하는 이유가 여기에 있습니다. 객체지향 프로그래밍은 프로그램의 퍼포먼스를 높이거나 개발시간 단축을 위한 프로그래밍 방법론이 아니라 유지보수를 잘 하기 위한 개발 방법론입니다. 객체지향 프로그래밍 방법론을 적용해가며 프로그래밍을 하다 보면 절차지향 프로그래밍에 비해 오히려 코딩 분량이 늘어나게 마련이고, (일반적으로) 퍼포먼스도 떨어지게 됩니다. 그러나 그 대신 우리는 유지보수의 편리성을 얻게 되는거죠.</p>
<p>자, 여러분이 코딩한 내용을 살펴보세요. 객체에 addEventListener() 달아놓은 이벤트 리스너와 핸들러 그리고 그에 속한 관련 처리 함수가 전체 코딩 분량의 절반을 넘는다면, 그것은 AS2.0의 타임라인 날코딩과 다를 바 없을겁니다. 이런 경우 AS3.0 으로 코딩하고는 있지만 객체지향적인 프로그래밍으로 인한 이득을 얻지 못하는 경우라고 할 수 있을 겁니다. 그래서 좀더 OOP적으로 프로그래밍 하기 위해, 그리고 조금더 이 (개발)언어를 마치 모국어를 말하듯 구사하기 위해, 이런 주제를 잡았습니다.</p>
<p>그리고 이 포스팅들은 <a href="http://cafe.naver.com/pfgroup">제가 참여하고 있는 스터디</a>, 또는 세미나에서 발표한 내용을 청중들에게 미리 자료로 제공하기 위해 초고(草稿) 형태로 작성한 내용이기도 합니다. 발표가 끝난 후 조금 더 정리하거나 내용을 추가해서이 블로그에 포스팅 되므로, 포스팅 되는 시점은 실제 글이 쓰여진 시점보다는 약간 나중이 될 가능성이 높습니다.</p>
<p>또한, 애당초 발표를 목적으로 글이 쓰여지기 때문에 실제 학습순서와는 다르게 포스팅 될 수 있습니다. 예컨대 &#8220;상속&#8221;을 이해 한 후 &#8220;다형성&#8221; 을 읽어보면 좀 더 이해가 잘 되겠지만, 실제 순서는 &#8220;다형성&#8221; 이 먼저 포스팅 될 수 있다는 것이죠. 이런 경우 나중에 포스팅 된 &#8220;상속&#8221; 을 읽으신 후, 예전에 포스팅 되었던 &#8220;다형성&#8221;을 한 번더 읽어 보실 필요도 있을 것입니다.</p>
<p>어쨌건, 현재까지 작성되었거나 계획중인 포스팅은 아래와 같습니다. (rss 로 이 글을 보시는 분들은 아래의 포스트 목록이 주기적으로 추가되거나 바뀐다는 것을 기억하세요.)</p>
<blockquote>
<h4>OOP in ActionScript (액션스크립트에서의 OOP)</h4>
<ol>
<li><a href="http://ufx.kr/blog/539">예제를 통해 쉽게 풀어보는 OOP의 다형성 (Polymorphism)</a></li>
<li><a href="http://ufx.kr/blog/570">액션스크립트로 하는 객체 재사용(재활용)과 오브젝트 풀(Object Pool) &#8211; 개요</a></li>
<li><a href="http://ufx.kr/blog/583">플래시 플레이어의 가비지 컬렉션(gabage collection)에 대한 이해</a></li>
<li><a href="http://ufx.kr/blog/591">액션스크립트의 객체 재사용을 위한 오브젝트 풀(Object Pool)</a></li>
</ol>
</blockquote>
<p>그리고<a href="http://ufx.kr/blog/category/flashpaltform/oop"> OOP에 대한 시리즈 포스트</a>는 <a href="http://ufx.kr/blog/category/flashpaltform/beginner-as3">고수들은 가르쳐주지 않는 AS3.0 입문</a> 카테고리에도 포함될 예정이므로, 초보 개발자들도 이해하기 쉬운 내용과 고수들은 잘 가르쳐 줄것 같지 않은 특별한 요점정리로 포스트가 쓰여질 내용입니다. 따라서 OOP 에 이미 익숙한 개발자 분들은 딱히 이 시리즈를 읽지 않으셔도 됩니다.</p>
<p>그럼 먼저 OOP의 기본 요소들과 개념들은 무엇인지 나열해 보도록 합시다.</p>
<ul>
<li>Classes : 클래스</li>
<li>Instance :인스턴스</li>
<li>Method : 메서드</li>
<li>Message passing : 메시지 패싱 (전달)</li>
<li>Decoupling : 디커플링</li>
<li>Abstraction : 추상화</li>
<li>Inheritance : 상속</li>
<li>Encapsulation : 은닉(캡슐화)</li>
<li>Polymorphism : 다형성</li>
</ul>
<p>이중에서도 OOP의 3대 속성이라고 한다면</p>
<ol>
<li> 상속</li>
<li> 은닉(캡슐화)</li>
<li> 다형성</li>
</ol>
<p>을 꼽을 수 있고, 이 목록은 OOP를 주제로 쓰여질 포스트들의 주제 목록에 다름 아닙니다. 모든 주제를 다루진 않겠지만 대체로 위의 목록이 가리키는 범주를 벗어나지 않는 개념 향상 위주의 포스팅이 예정되어 있습니다.</p>
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/510/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>순환문과 인스턴스네임 다시 생각해보기</title>
		<link>http://ufx.kr/blog/485</link>
		<comments>http://ufx.kr/blog/485#comments</comments>
		<pubDate>Fri, 27 Aug 2010 10:07:26 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[순환문]]></category>
		<category><![CDATA[인스턴스네임]]></category>
		<category><![CDATA[컬렉션]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=485</guid>
		<description><![CDATA[부제: AS2.0의 인스턴스 네이밍 습관을 AS3.0에서 바꿔보자. 액션스크립트로 처음 개발언어에 입문한 사람들에게 순환문은 마법과도 같은 생산성을 의미합니다. 스테이지와 타임라인에 드로잉 툴로 이것저것 그려내고 모션 트윈이나 쉐이프 트윈 노가다를 하던때가 매우 미개하게 느껴질 만큼 그 위력은 대단하게 느껴지죠. 액션스크립트에서 사용할 수 있는 순환문에는 while, do .. while, for, for .. in, for each .. in 의 [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_486" class="wp-caption alignleft" style="width: 250px"><img class="size-full wp-image-486" title="loop_image" src="http://ufx.kr/blog/wp-content/uploads/2010/08/loop_image.jpg" alt="" width="240" height="180" /><p class="wp-caption-text">순환문만 있다면 수백만번의 반복 노가다도 문제 없다.</p></div>
<h4>부제: AS2.0의 인스턴스 네이밍 습관을 AS3.0에서 바꿔보자.</h4>
<p>액션스크립트로 처음 개발언어에 입문한 사람들에게 순환문은 마법과도 같은 생산성을 의미합니다. 스테이지와 타임라인에 드로잉 툴로 이것저것 그려내고 모션 트윈이나 쉐이프 트윈 노가다를 하던때가 매우 미개하게 느껴질 만큼 그 위력은 대단하게 느껴지죠.</p>
<p>액션스크립트에서 사용할 수 있는 순환문에는 while, do .. while, for, for .. in, for each .. in 의 다섯가지 입니다.<sup>[<a href="http://ufx.kr/blog/485#footnote_0_485" id="identifier_0_485" class="footnote-link footnote-identifier-link" title="for each .. in 순환문은 AS3.0에서 추가되었으므로 AS2.0에서는 사용하지 못합니다.">01</a>]</sup> 앞의 세 가지 순환문은 각기 형태가 다르게 보이지만 조건이 true 일 동안 계속 실행된다는 원리나 동작 방식이 동일하고, 뒤의 두 가지 순환문은 객체의 모든 변수(또는 객체가 가진 자식 객체)에 개별적으로 접근할 수 있는 특징을 가지고 있습니다.</p>
<p>다섯 가지의 순환문이 있음에도 불구하고 뭔가 코드에 관여하여 컨트롤 할 수 있는 부분이 많아 보여서 일까요? 대부분의 초보 개발자들은 for 순환문만 주구장창 사용합니다. 그것도 조건을 조회하는데 i++ 와 같이 정수 i 값을 증가하거나 감소하는 방식만 사용하죠.</p>
<p><span id="more-485"></span></p>
<p>그러면 이런 for 문은 어떤가요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> list<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span> <span style="color: #990000;">&quot;a&quot;</span>, <span style="color: #990000;">&quot;b&quot;</span>, <span style="color: #990000;">&quot;c&quot;</span> <span style="color: #000000;">&#93;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>;
<span style="color: #0033ff; font-weight: bold;">for</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; hasNext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#41;</span> <span style="color: #009900;">// 조건절의 모양새에 유의</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> getItem<span style="color: #000000;">&#40;</span> i <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #339966; font-weight: bold;">function</span> <span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
<span style="color: #000000;">&#123;</span>
	i = <span style="color: #000000; font-weight:bold;">0</span>;
	<span style="color: #009900;">// some initialize</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #339966; font-weight: bold;">function</span> hasNext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Boolean</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> list.<span style="color: #004993;">length</span> <span style="color: #000000; font-weight: bold;">&gt;</span> i <span style="color: #000000;">&#41;</span>
		<span style="color: #0033ff; font-weight: bold;">return</span> <span style="color: #0033ff; font-weight: bold;">true</span>;
	<span style="color: #0033ff; font-weight: bold;">else</span>
		<span style="color: #0033ff; font-weight: bold;">return</span> <span style="color: #0033ff; font-weight: bold;">false</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #339966; font-weight: bold;">function</span> getItem<span style="color: #000000;">&#40;</span> $index<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:*</span>
<span style="color: #000000;">&#123;</span>
	i<span style="color: #000000; font-weight: bold;">++</span>;
	<span style="color: #0033ff; font-weight: bold;">return</span> list<span style="color: #000000;">&#91;</span> $index <span style="color: #000000;">&#93;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위의 코드는 유효한 코드 입니다. 반드시 for( i = 0; i < n; ++i ) 의 형태일 필요가 없다는 것이죠. for 문 괄호안의 세미콜론으로 구분되는 세 부분은 왼쪽부터 초기화, 조건절, 루프 후 실행이라는 각각의 역할을 가지고 있습니다. 그런데 for 문은 실제로 가운데의 조건절 부분만 만족하면 앞뒤 부분은 생략되도 문법적으로 에러가 아닙니다. 즉, for( ; hasNext(); ) 이런 for 문 역시 유효합니다.</p>
<p>그러나 이렇게 사용할 바에야 while 문을 사용하는게 퍼포먼스 면에서라도 조금이나마 나을겁니다. 즉, for 문이 while 문에 비해 추가된 기능은 바로 조건절 앞 뒤에 존재하는 부분입니다. for 문은 초기화와 루프 후 실행을 한 줄에 지정할 수 있다는 잇점을 가지고 있습니다. 반대로 초기화할 필요가 없고 루프 후 실행할 것이 없으면 while 문을 사용하는것을 고려해 볼 필요가 있습니다.</p>
<p style="text-align: center;">* * * * *</p>
<h3>A. 문제점 제시</h3>
<p>자 그럼 슬슬 순환문 사용에 있어서의 문제점을 살펴볼까요?<br />
초보 개발자들은 for( i = 0; i < n; ++i ) 형태의 순환문만을 사용하려는 습관을 가지고 있는데, 이 습관 때문에 AS2.0에서는 객체들에게 거의 예외없이 "문자열"+숫자 형태의 일련번호를 가진 인스턴스네임이 늘상 사용되어 왔습니다. 이것은 다분히 플래시가 디자이너들에 의해 네비게이션 바를 만드는 툴로 인식되면서부터 습관이 되버린 사용 방법이면서, 동시에 fla 파일을 판매하는 몇몇 사이트에서 네비게이션 바를 만들때 어김없이 사용한 방식이기도 했습니다. 심지어 Flash 8 까지는 숫자만으로 이루어진 인스턴스네임조차도 허용되었기 때문에,<sup>[<a href="http://ufx.kr/blog/485#footnote_1_485" id="identifier_1_485" class="footnote-link footnote-identifier-link" title="물론, 현재는 숫자만으로 이루어지거나 숫자로 시작하는 인스턴스네임은 허용되지 않습니다.">02</a>]</sup> 네비게이션 항목 객체의 인스턴스네임이 죄다 숫자로 이루어진 엽기적인 fla 파일들도 한동안 돌아다니곤 했습니다.</p>
<p>그런 네비게이션 바를 만들어낸 사이트들을 탓할 생각은 없습니다. AS2.0 이하의 구조에서는 아주 간단하고 효율적으로 객체를 참조할 수 있는 방법중 하나였으니까 말이죠. 문제는 이런 방법에 익숙해진 디자이너들이 이 방법 이외에는 생각을 하지 않는다는 것입니다.</p>
<p>그럼 그렇게 된 원인을 오랜만에 AS2.0 코드를 보면서 짚어볼까요?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// fla 의 상황. 라이브러리에 Linkage 이름을 mc 으로 부여한 무비클립이 있음</span>
<span style="color: #000000; font-weight: bold;">var</span> temp:<span style="color: #0066CC;">MovieClip</span>;
<span style="color: #000000; font-weight: bold;">var</span> len:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">10</span>;
<span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span> i = <span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> len; ++i <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
	temp = <span style="color: #0066CC;">this</span>.<span style="color: #0066CC;">attachMovie</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;mc&quot;</span>, <span style="color: #ff0000;">&quot;mc&quot;</span> + i, <span style="color: #0066CC;">this</span>.<span style="color: #0066CC;">getNextHighestDepth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
	temp.<span style="color: #0066CC;">_x</span> = <span style="color: #66cc66;">&#40;</span> temp.<span style="color: #0066CC;">_width</span> + <span style="color: #cc66cc;">5</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> i;
	<span style="color: #808080; font-style: italic;">// 그 밖의 초기화 코드</span>
&nbsp;
	<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> temp.<span style="color: #0066CC;">_name</span> <span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></td></tr></table></div>

<p>이렇게 하면 화면에 mc0 부터 for 문이 돌아간 마지막 i 값까지의 객체가 다다닥 생겼을겁니다.</p>
<div id="attachment_487" class="wp-caption aligncenter" style="width: 540px"><img class="size-full wp-image-487" title="as2ex" src="http://ufx.kr/blog/wp-content/uploads/2010/08/as2ex.png" alt="" width="530" height="57" /><p class="wp-caption-text">컴파일 결과 화면 상황</p></div>
<p>이 순환문이 한번 돌아간 이후로는 this 의 어디에서나 mc0, mc1, mc2 &#8230; mc9 를 참조할 수 있습니다. 그것인 즉, 인스턴스 객체가 만들어지면서 같은 이름의 인스턴스네임도 부여되었다는 것을 의미 합니다.</p>
<p>이 상황에서 아래와 같은 코드를 실행해보도록 합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
</pre></td><td class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">this</span>.<span style="color: #006600;">mc2</span>.<span style="color: #0066CC;">_name</span> = <span style="color: #ff0000;">&quot;ufx&quot;</span>; <span style="color: #808080; font-style: italic;">// 이렇게 mc2 의 _name 속성을 변경하면</span>
<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0066CC;">this</span>.<span style="color: #006600;">mc2</span> <span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 출력 : undefined</span>
<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> <span style="color: #0066CC;">this</span>.<span style="color: #006600;">ufx</span> <span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 출력 : _level0.ufx</span></pre></td></tr></table></div>

<p>이 코드를 보고 무엇을 알 수 있나요? AS2.0 에서 객체의 인스턴스네임과 _name 속성은 같은것을 지칭한다라는 것을 말해주고 있습니다.</p>
<p style="text-align: center;">* * * * *</p>
<h3>B. 그러나 AS3.0에 와서는 사정이 달라졌습니다.</h3>
<p>AS3.0에서는 fla 의 편집 화면상에 존재하는 무비클립에 인스턴스네임을 부여하면, 런타임에 name 속성을 변경할수가 없습니다. name 속성 변경을 시도하면 아래와 같은 에러 메세지를 만날 수 있습니다.</p>
<blockquote><p>Error: Error #2078: 타임라인에 위치한 객체의 이름 속성은 수정할 수 없습니다.<br />
at flash.display::DisplayObject/set name()<br />
at AS3Test_fla::MainTimeline/frame1()</p></blockquote>
<p>게다가 코드상에서 new 키워드를 사용하여 라이브러리의 클래스 정의를 사용하여 객체를 생성하는 경우, 인스턴스네임을 임의로 부여할 수가 없습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> temp<span style="color: #000000; font-weight: bold;">:</span>TagImage;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> len<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> = <span style="color: #000000; font-weight:bold;">10</span>;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> len; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	temp = <span style="color: #0033ff; font-weight: bold;">new</span> TagImage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	temp.<span style="color: #004993;">x</span> = temp.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
	<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> temp <span style="color: #000000;">&#41;</span>;
&nbsp;
	<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> temp.<span style="color: #004993;">name</span> <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위에서 보는것과 같이 name 속성은 별도로 코딩해서 속성부여하지 않는다면 swf 파일을 컴파일 하는 시점에서 아래와 같이 컴파일러가 자동으로 name 값을 부여하게 됩니다.</p>
<blockquote><p>
trace( temp.name ) 출력 결과</p>
<p>instance1<br />
instance3<br />
instance5<br />
instance7<br />
instance9<br />
instance11<br />
instance13<br />
instance15<br />
instance17<br />
instance19
</p></blockquote>
<p>그렇다면 인스턴스네임은? 알 수 없습니다. 알 수도 없고 지정하거나 수정할 수도 없습니다. 즉, 인스턴스네임을 부여할 수 있는 경우는 fla 의 스테이지 화면에 존재하는 무비클립을 선택한 상태에서 속성 패널을 이용하는 경우로 제한되어 있는 것이죠.</p>
<p><span style="color: #E08427;">AS3.0과 AS2.0이 가장 확연한 차이를 보이는 것 중 하나가 바로 이 부분</span> 입니다. AS2.0 으로 플래시를 접했던 많은 사람들은 이 부분을 가장 혼동하게 되고, 이렇다는 것을 나중에 알게된 후에는 &#8220;정말 불편하게 변경되었잖아&#8221; 라고 생각합니다. 모든 무비클립을 인스턴스네임으로 핸들링해 왔는데 갑자기 그것이 제한되니까 그렇게 생각하는것도 당연합니다. 당장 this[ "mc" + i ] 스타일로 인스턴스네임을 줄 수가 없으므로, 뭘 하고 싶어도 할 수 없는 그런 상황이 된 것이죠.</p>
<p>그러나 실제로 인스턴스네임에는 다음과 같은 두 가지 문제가 있습니다.</p>
<ul>
<li>서로다른 객체에게 같은 인스턴스네임을 부여할 수 있습니다. (인스턴스네임이 중복되었는데 에러를 내지 않습니다.)</li>
<li>중복된 인스턴스네임을 핸들링하면 먼저생성된 객체만 핸들링됩니다.</li>
</ul>
<p>이런 부정확성은 객체를 핸들링 하는데 신뢰도를 떨어뜨리게 되어 원하지 않는 결과를 가지고 올 수 있게 됩니다. 그리고 이런 에러는 디버깅 하기도 힘들겠군요.</p>
<p>그래서 AS3.0에서는 인스턴스네임 대신 객체를 핸들링 하는 다른 방법들을 사용하게 됩니다. 그 방법들을 알아보기 전에 다시 한번 생각해보고 넘어가야할 것이 있습니다.</p>
<p style="text-align: center;">* * * * *</p>
<h3>C. 정말 넘버링(Numbering)을 해야만 하는가?</h3>
<p>AS2.0시절 인스턴스네이밍을 할때 &#8220;mc&#8221; + i 스타일로 하는것에 대해서 인데요, 대체 무엇때문에 넘버링을 하는 걸까요?</p>
<p>넘버링을 하는 이유는 두 가지로 볼 수 있습니다. 인스턴스네임이 중복되지 않게 유니크한 값을 가지기 위함이 첫번째 이유이고, 인스턴스네임을 substr() 메서드 등으로 문자열 조작을 하여 숫자부분 만을 획득한 후 그것을 index 로 다른 행동이나 값들을 호출하기 위함이 두 번째 이유 입니다.</p>
<p>그러나 다른 객체와 구분하기 위함이라면 &#8220;menu1&#8243; 보다는 &#8220;AboutCompany&#8221; 가 훨씬 알아보기 쉽잖아요. trace() 찍어볼때는 말할것도 없습니다.<br />
또한 넘버링을 한다는 것은 숫자가 인덱스의 의미를 가져 객체간 구분을 하는 기준을 삼는다는 것을 의미합니다. 그런데 정말 숫자가 의미를 가지고 있습니까? &#8220;mc&#8221; + i 스타일 네이밍에서 i 값은 단지 객체간 구분을 하고 어떤것을 먼저 생성했는지 순서를 말해줄 뿐, 숫자가 가지는 실제적인 의미가 없습니다.</p>
<p>그러므로 인스턴스네임을 넘버링 하는것에 더 이상 미련을 두지 마세요. 우리는 그 객체의 이름조차 알 필요 없는 더 좋은 방법을 사용하게 될 테니까요.</p>
<p style="text-align: center;">* * * * *</p>
<h3>D. 상황별 해결 방법.</h3>
<p>자, 그럼 다음의 세 가지 방식의 솔루션을 제시합니다. 경우에 따라서 특정한 상황에는 반드시 특정한 방법을 사용해야만 할 수 있습니다만, 대체로 여러분의 입맛에 맞는 방법을 사용하면 됩니다.</p>
<h4>D-1. AS2.0 방식으로 사용하기를 원한다. (name 속성을 인스턴스네임 대신 사용)</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>, len<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">5</span>;
<span style="color: #0033ff; font-weight: bold;">for</span><span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> len; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;item&quot;</span> <span style="color: #000000; font-weight: bold;">+</span> i; <span style="color: #009900;">// 이렇게 name 속성에 넘버링</span>
	<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위와같이 객체들을 생성했으면,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem = <span style="color: #004993;">getChildByName</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;item1&quot;</span> <span style="color: #000000;">&#41;</span> <span style="color: #0033ff; font-weight: bold;">as</span> MenuItem;
item.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// 물론 DisplayObject 수준의 속성을 제어하는 거라면 간단하게 아래와 같이 해도 됩니다.</span>
<span style="color: #004993;">getChildByName</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;menu1&quot;</span> <span style="color: #000000;">&#41;</span>.<span style="color: #004993;">y</span> = <span style="color: #000000; font-weight:bold;">10</span>;</pre></td></tr></table></div>

<p>위와 같이 DisplayObjectContainer 클래스의 getChildByName() 메서드를 이용해 name 속성으로 객체를 잡아낼 수 있습니다.</p>
<h4>D-2. 배열(Array)에 넣어라</h4>
<p>그러나 name 속성은 인스턴스네임과 마찬가지로 서로 다른 객체가 동일한 name 을 가지는것이 허용됩니다. 객체를 생성할때야 &#8220;이런게 헷갈릴리가 없어&#8221; 라고 생각하지만, 우리&#8230; 평생 네비게이션만 만들거 아니잖아요. 엔터프라이즈급의 복잡한 시스템을 가진 플래시 애플리케이션이라면 name 속성이 중복되는 일이 보기 드문 일도 아닙니다.</p>
<p>그래서 보통 이런경우 플래시 개발자들은 가장 손쉬운 방법으로 배열을 사용합니다. 우리가 제어하고 싶어하는 일련의 비슷한 객체들은 배열에 넣어서 관리하는 것이 가장 손이 덜 가고 편리한 방법 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>, len<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">5</span>;
<span style="color: #0033ff; font-weight: bold;">for</span><span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> len; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	itemList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 배열에 push()</span>
	<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위와같이 객체 생성 시점에 배열에 넣어두고</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem = itemList<span style="color: #000000;">&#91;</span> <span style="color: #000000; font-weight:bold;">1</span> <span style="color: #000000;">&#93;</span>;
item.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">//배열 원소는 실제 객체를 참조하고 있기 때문에 별도의 캐스팅 없이 간단하게 아래와 같이 사용할 수도 있습니다. 단, 개발환경에 따라 코드힌트를 받지 못할수도 있습니다.</span>
itemList<span style="color: #000000;">&#91;</span> <span style="color: #000000; font-weight:bold;">1</span> <span style="color: #000000;">&#93;</span>.<span style="color: #004993;">y</span> = <span style="color: #000000; font-weight:bold;">10</span>;</pre></td></tr></table></div>

<p>위와같이 배열 연산자로 각 객체를 참조할 수 있습니다.</p>
<h4>D-3. Object에 넣는것은 좀더 세련된 방법</h4>
<p>Object 클래스는 모든 클래스의 원형 클래스이기 때문에 이런저런 제한이 가장 덜 걸려 있는 클래스 입니다. 제한이 별로 없는 반면 할 수 있는 일역시 별로 없기도 하죠. 시각적인 면만을 본다면 Object 객체는 실제로 스테이지에 보이게 할 수 있는 것도 아니고 추상적인 특성을 가지고 있기 때문에 그리 쓸모가 없어 보이기도 합니다만, 반대로 이러한 유연한 특성 때문에 데이터를 저장하고 읽어내는데 편리한 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>, len<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">5</span>;
<span style="color: #0033ff; font-weight: bold;">for</span><span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> len; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
	<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
	itemList<span style="color: #000000;">&#91;</span> <span style="color: #990000;">&quot;id&quot;</span> <span style="color: #000000; font-weight: bold;">+</span> i <span style="color: #000000;">&#93;</span> = item;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이렇게 생성한 후에는,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> itemList.id1 <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력 : [object MenuItem]</span>
itemList.id1.<span style="color: #004993;">y</span> = <span style="color: #000000; font-weight:bold;">100</span>; <span style="color: #009900;">// 이렇게 속성에도 자유롭게 접근됩니다.</span></pre></td></tr></table></div>

<p>다른 방법들보다 훨씬 직관적인데다가 간편하게 사용할수 있습니다.<br />
이런 기능은 정확하게는 Object 클래스가 dynamic 으로 정의되어 있기 때문에 가능한 것인데, 반드시 Object 클래스가 아니더라도 dynamic 으로 정의되어 있는 MovieClip 과 같은 클래스도 동일하게 사용할 수 있습니다. 다만, 변수와 값을 보관하는데 MovieClip 씩이나 사용할 필요가 없겠죠. 게다가 이런 용도로 이미 많은 개발자들이 Object 를 사용하고 있기 때문에 코드 가독성을 고려해 봤을때 플래시 네이티브 클래스 중에서는 Object 클래스가 가장 좋은 선택이라고 할 수 있습니다.</p>
<p style="text-align: center;">* * * * *</p>
<h3>E. for each .. in 을 이용한 순환문의 활용</h3>
<p>지금까지 객체들을 생성하고 특정한 방식에 의해 세팅하는것을 살펴봤습니다. 이렇게 세팅하는것을 설명한 이유는, 활용을 할때 제대로 활용하기 위함이죠.<br />
위에서 제시한 방법 중 getChildByName() 을 제외한 나머지 두 가지 방법은 객체들을 목록(컬렉션)으로 받게 됩니다. 이런 경우 for each .. in 순환문을 사용하게 되면 훨씬 신뢰성이 좋은 순환문을 만들 수 있습니다.<br />
아래 코드는 for each .. in 순환문의 특성을 명확하게 표현하기 위해, 파싱된 xml 객체를 이용했습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> xml<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">XML</span> =
<span style="color: #000000; font-weight: bold;">&lt;</span>data<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>첫번째 메뉴<span style="color: #000000; font-weight: bold;">&lt;/</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>path<span style="color: #000000; font-weight: bold;">/</span>myurl_1.html<span style="color: #000000; font-weight: bold;">&lt;/</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>_self<span style="color: #000000; font-weight: bold;">&lt;/</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;/</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>두번째 메뉴<span style="color: #000000; font-weight: bold;">&lt;/</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>path<span style="color: #000000; font-weight: bold;">/</span>myurl_2.html<span style="color: #000000; font-weight: bold;">&lt;/</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>_self<span style="color: #000000; font-weight: bold;">&lt;/</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;/</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>세번째 메뉴<span style="color: #000000; font-weight: bold;">&lt;/</span>name<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>path<span style="color: #000000; font-weight: bold;">/</span>myurl_3.html<span style="color: #000000; font-weight: bold;">&lt;/</span>url<span style="color: #000000; font-weight: bold;">&gt;</span>
		<span style="color: #000000; font-weight: bold;">&lt;</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>_blank<span style="color: #000000; font-weight: bold;">&lt;/</span>target<span style="color: #000000; font-weight: bold;">&gt;</span>
	<span style="color: #000000; font-weight: bold;">&lt;/</span>menu<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">&lt;/</span>data<span style="color: #000000; font-weight: bold;">&gt;</span>;
&nbsp;
<span style="color: #6699cc; font-weight: bold;">var</span> itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem, node<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">XML</span>, i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> node <span style="color: #0033ff; font-weight: bold;">in</span> xml.menu <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	<span style="color: #009900;">//item.updateXml( node ); // 이런식으로 XML 을 객체로 넘겨 내부에서 url 등을 처리하도록 함</span>
	i = node.<span style="color: #004993;">childIndex</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// index 값이 필요하면 xml 의 childIndex() 를 사용</span>
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
	item.txtName.<span style="color: #004993;">text</span> = item.<span style="color: #004993;">name</span> = node.<span style="color: #004993;">name</span>;
	<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
&nbsp;
	itemList<span style="color: #000000;">&#91;</span> i <span style="color: #000000;">&#93;</span> = item;
&nbsp;
	<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> item.<span style="color: #004993;">name</span> <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이런 예제는 실무에 사용되는 코드와 거의 비슷하다고 할 수 있겠죠. xml 을 이용해 for each .. in 순환문을 사용하는 경우 xml 의 노드 순서대로 순환문이 돌기 때문에 순서대로 배열에 들어가게 됩니다.<br />
배열에 예쁘게 들어가있기 때문에 사용하는것도 매우 편리합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> item <span style="color: #0033ff; font-weight: bold;">in</span> itemList <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> item.<span style="color: #004993;">name</span> <span style="color: #000000;">&#41;</span>;
	item.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>실제로 for each .. in 순환문은 for( i = 0; i < len; ++i ) 스타일의 for 순환문에 비해서 훨씬 직관적으로 사용할 수 있고, 순환 조건 평가가 undefined, NaN 또는 null 이 대입되서 무한루프에 빠지는 경우가 발생하지 않아 에러 발생이 획기적으로 줄어듭니다. 정확히 필요한 만큼만 순환하고 알아서 루프를 끝내기 때문이죠. 또한 속도 테스트를 해봐도 for 순환문보다 약간 빠릅니다.</p>
<p>그런데 한 가지 주의할 점이 있습니다. 배열의 경우 index 0번부터 순서대로 for each .. in 이 돌지만, 저 위의 경우와 같이 Object 에 변수로 저장한 경우에는 순서를 보장해주지는 않습니다. <span style="color: #E08427;">Object 를 컬렉션으로 사용하는 경우에는 실행 순서가 관계없는 순환문에 한정해서 사용해야 합니다.</span></p>
<p style="text-align: center;">* * * * *</p>
<h3>F. 그런데 코딩하다보면 index 가 필요하던데?</h3>
<p>먼저 객체간의 index 가 정말 필요한가 다시 생각해볼 필요가 있습니다. for each .. in 순환문은 컬렉션의 모든 변수(또는 원소)를 순환하기 때문에 index 가 필요하지 않습니다. 만약 여러분이 순환문만을 루프 시키기 위한, i++ 를 생각하고 있다면 더이상 i 를 사용할 필요가 없습니다.</p>
<p>그런데 객체간의 index 값이 필요할 때가 있긴 있습니다. 가장 손쉽게 떠오르는 경우는 객체의 width 속성을 i 로 곱해서 일렬로 주욱 나열하고 싶을 때가 해당하겠죠. 그런 경우에는 컬렉션의 여러가지 index를 활용할 수 있습니다.</p>
<h4>F-1. 별도의 변수 index++ 를 사용.</h4>
<p>보통의 for 문을 순환시키는 것과 동일한 테크닉입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">0</span>;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> item <span style="color: #0033ff; font-weight: bold;">in</span> itemList <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
	i<span style="color: #000000; font-weight: bold;">++</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>F-2. XML 노드는 childIndex()</h4>
<p>XML 노드를 순환할 경우에는 저 위쪽에서 이미 본 것과 같이 childIndex() 메서드를 사용하는 방법도 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> node<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">XML</span>, i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> node <span style="color: #0033ff; font-weight: bold;">in</span> xml.menu <span style="color: #000000;">&#41;</span> <span style="color: #009900;">// XML 을 순환하고 있음에 유의</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	i = node.<span style="color: #004993;">childIndex</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>F-3. Array 는 indexOf()</h4>
<p>배열의 경우라면 indexOf() 메서드가 있겠죠.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
<span style="color: #009900;">// 배열에 객체 생성하고 넣는 과정 코드는 생략</span>
&nbsp;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> item <span style="color: #0033ff; font-weight: bold;">in</span> itemList <span style="color: #000000;">&#41;</span> <span style="color: #009900;">// 배열을 순환하고 있음에 유의</span>
<span style="color: #000000;">&#123;</span>
	i = itemList.<span style="color: #004993;">indexOf</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>F-4. Object는 변수에 넘버링.</h4>
<p>Object는 위에서 이미 설명한대로, 순서가 보장되지 않으므로, 변수명에 넘버링을 하는 방법을 택하는것이 좋습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> itemList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #009900;">// 객체 생성하고 Object에 넣는 과정 코드는 생략</span>
<span style="color: #009900;">// Object 내부에 생성된 변수명은 item0, item1, ... </span>
&nbsp;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem;
<span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> len<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">10</span>; <span style="color: #009900;">// 객체를 생성한 갯수를 저장 (예시)</span>
<span style="color: #0033ff; font-weight: bold;">for</span><span style="color: #000000;">&#40;</span> i = <span style="color: #000000; font-weight:bold;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> len; <span style="color: #000000; font-weight: bold;">++</span>i <span style="color: #000000;">&#41;</span> <span style="color: #009900;">// for each..in 순환문은 Object 내부의 변수를 순차적으로 순환하지 못하므로 index를 이용해 순환하고 있음에 유의</span>
<span style="color: #000000;">&#123;</span>
	item = itemList<span style="color: #000000;">&#91;</span> <span style="color: #990000;">&quot;item&quot;</span> <span style="color: #000000; font-weight: bold;">+</span> i <span style="color: #000000;">&#93;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h4>F-5. DisplayObjectContainer는 getChildIndex()</h4>
<p>DisplayObjectContainer 의 getChildIndex() 메서드를 이용해서 Sprite 객체에 addChild() 된 자식들의 index 를 이용하는 방법도 생각해 볼 수 있는 방법 중 하나 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// xml 객체는 생략</span>
<span style="color: #6699cc; font-weight: bold;">var</span> container<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> item<span style="color: #000000; font-weight: bold;">:</span>MenuItem, node<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">XML</span>, i<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>;
<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span><span style="color: #000000;">&#40;</span> node <span style="color: #0033ff; font-weight: bold;">in</span> xml.menu <span style="color: #000000;">&#41;</span> <span style="color: #009900;">// XML 을 순환하고 있음에 유의</span>
<span style="color: #000000;">&#123;</span>
	item = <span style="color: #0033ff; font-weight: bold;">new</span> MenuItem<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	container.<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
	i = container.<span style="color: #004993;">getChildIndex</span><span style="color: #000000;">&#40;</span> item <span style="color: #000000;">&#41;</span>;
	item.<span style="color: #004993;">x</span> = item.<span style="color: #004993;">width</span> <span style="color: #000000; font-weight: bold;">*</span> i;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: center;">* * * * *</p>
<p>여기까지 인스턴스네임과 순환문과의 관계 부터, AS3.0 개발 과정에서 만나게 될 수 있는 여러가지 상황에 따른 보다 적절한 순환문의 사용까지 두루두루 살펴봤습니다. 실제 여러분들의 코딩 수준은 천차만별일지라도, 저는 글을 쓸때 여러분을 어느정도 일정한 범위로 특정한 후에 쓰고 있습니다. 그렇지 않으면 이도저도 아닌 이해하기 힘든 글이 되기 쉽상이니까요. 그러나 역시 제 블로그의 대부분의 글은 초보 개발자들에 포커스가 맞춰져 있죠. 게다가 이 글은 좀더 초보 개발자의 시각에서 바라보고 글을 썼습니다. 글의 소재가 그러하였으니까요. ^^</p>
<p>그러나 이렇게 끝내면 이 글이 쉽게 느껴지는 개발자 분들은 섭섭해 하실것 같아, 바로 이어서 속편이 이어지겠습니다.</p>
<ol class="footnotes"><li id="footnote_0_485" class="footnote">for each .. in 순환문은 AS3.0에서 추가되었으므로 AS2.0에서는 사용하지 못합니다.</li><li id="footnote_1_485" class="footnote">물론, 현재는 숫자만으로 이루어지거나 숫자로 시작하는 인스턴스네임은 허용되지 않습니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/485/feed</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>액션스크립트 초보를 위한 코딩 기본 규칙, 네이밍, 이것만은 지키자.</title>
		<link>http://ufx.kr/blog/414</link>
		<comments>http://ufx.kr/blog/414#comments</comments>
		<pubDate>Thu, 20 May 2010 22:45:53 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[pascal]]></category>
		<category><![CDATA[var]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[변수]]></category>
		<category><![CDATA[상수]]></category>
		<category><![CDATA[언더스코어]]></category>
		<category><![CDATA[인터페이스]]></category>
		<category><![CDATA[캐멀]]></category>
		<category><![CDATA[코드힌트]]></category>
		<category><![CDATA[코딩]]></category>
		<category><![CDATA[클래스]]></category>
		<category><![CDATA[파스칼]]></category>
		<category><![CDATA[표기법]]></category>
		<category><![CDATA[함수]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=414</guid>
		<description><![CDATA[요즘도 만드는지는 모르겠지만, 이소룡과 성룡이 전성기였던 시절 쿵푸를 소재로 한 영화들을 보면 대략 이런 스토리가 진행됩니다. 집안이 원수들에게 유린당하고 주인공만 홀로 남게 되었는데, (우연한) 기회에 절정고수의 무술 사부님을 만나, 혹독한 수련을 받은 후, 하산하여 원수를 갚는다. 라는 이야기죠. 쿵푸영화들의 절반 이상은 항상 이런식이었는데도 질리지도 않고 계속 비슷한 스토리의 영화가 나왔던것 같습니다. 영화의 전개 부분에는 사부님으로부터 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://ufx.kr/blog/wp-content/uploads/2010/05/kungfu_panda.jpg"><img class="alignleft size-full wp-image-415" title="kungfu_panda" src="http://ufx.kr/blog/wp-content/uploads/2010/05/kungfu_panda.jpg" alt="" width="179" height="240" /></a>요즘도 만드는지는 모르겠지만, 이소룡과 성룡이 전성기였던 시절 쿵푸를 소재로 한 영화들을 보면 대략 이런 스토리가 진행됩니다. 집안이 원수들에게 유린당하고 주인공만 홀로 남게 되었는데, (우연한) 기회에 절정고수의 무술 사부님을 만나, 혹독한 수련을 받은 후, 하산하여 원수를 갚는다. 라는 이야기죠. 쿵푸영화들의 절반 이상은 항상 이런식이었는데도 질리지도 않고 계속 비슷한 스토리의 영화가 나왔던것 같습니다.</p>
<p>영화의 전개 부분에는 사부님으로부터 배우는 혹독한 수련과정이 나오는데, 이 수련과정 또한 매우 스테레오타입인지라 마당쓸기, 물 길어오기, 빨래하기, 밥하기와 같은 허드렛 일을 열심히 했는데, 애초부터 책 같은 형태의 궁극의 비기(秘記) 따위는 없었고&#8230; 일견 쓸모 없어보였던 잡일이 알고보니 나중에 다 피가되고 살이되는 거였더라~ 라는 이야기 구성과 설정 또한 항상 같습니다.</p>
<p>오늘 다뤄볼 이야기는 이런 허드렛일과 비슷하고 기본 소양이 되는 그런 이야기 입니다. 코딩을 하다보면 이게 변수인지 파라미터인지 함수명인지 그것도 아니면 클래스명인지 알 수 없는 경험을 하고계신 분들이 있을겁니다.<br />
변수도, 이게 전역변수인지 지역변수인지, 전역변수라면 public 인지 protected 인지 private 인지 구분하고 싶은데 맨 위까지 스크롤 했다가 다시 내려오는걸 반복했다가는 코딩하다가 금방 지쳐 쓰러지겠죠.</p>
<p><span id="more-414"></span></p>
<div class="wp-caption alignright" style="width: 157px"><a href="http://blog.yes24.com/lib/adon/View.aspx?blogid=3435535&amp;goodsno=3100361&amp;idx=5655&amp;ADON_TYPE=B&amp;regs=b"><img title="액션스크립트 3.0 디자인 패턴" src="http://image.yes24.com/goods/3100361/147x215" alt="" width="147" height="215" /></a><p class="wp-caption-text">액션스크립트 3.0 디자인 패턴. 조이 로트,대니 패터슨 공저/정호연,양주일 공역</p></div>
<p>그래서 이런 경우 각 멤버들에 대한 네이밍 규칙을 정해 놓는다면, 코딩이 훨씬 수월해질 수 있다는거죠.<br />
제가 지금부터 써 내려가는 규칙들은 세계의끝이 고심끝에 정한 궁극의 네이밍 규칙&#8230;이 아니라 조이 로트와 대니 패터슨 공저, 액션스크립트 3.0 디자인 패턴(Advanced ActionScript 3 Design Patterns) 의 내용에 기술되어 있는 네이밍 규칙을 다시 정리하여 여러분에게 알려드리는 것입니다.<br />
이 책은 장호연씨의 번역과 양주일씨의 감수로 에이콘 출판사에서 번역서가 나와 있으므로 관심이 있는 분들은 읽어보시면 되겠습니다.</p>
<p>이 포스트에서 소개하게될 네이밍 규칙이 유일하고 절대적인 규칙이 아니라는 것을 책에서도 설명하고 있습니다. 이것은 다분히 스타일의 문제이고 가독성의 문제이지 프로그램 성능의 본질과는 직접적인 관계가 없기 때문입니다. 물론 내가 작성한 코드를 남이 볼 때 쪽이 덜 팔리는 부수적인(?) 효과정도는 보너스로 얻을 수 있을것 같습니다.<br />
네이밍에 대한 규칙은 41페이지부터 나와 있는 내용이므로 이 책에서도 가장 기본 단계의 지식으로 다루고 있는 셈 입니다.</p>
<p style="text-align: center;">* * *</p>
<h3>사용할 수 있는 문자</h3>
<p>액션스크립트에서 클래스, 패키지, 변수, 함수, 인터페이스를 네이밍할 때 사용할 수 있는 것으로는</p>
<ol>
<li>a부터 z까지 그리고 A부터 Z까지의 영문 문자열<sup>[<a href="http://ufx.kr/blog/414#footnote_0_414" id="identifier_0_414" class="footnote-link footnote-identifier-link" title="물론 액션스크립트는 uft-8 로 인코딩을 하므로 한글을 포함한 모든 언어의 문자열을 사용할 수 있으나 여러 가지 문제가 생길 수 있는 여지가 있으므로 영문 문자열로 네이밍을 제한하는 것이 좋습니다. 이에 해당하는 내용은 차후 별도의 포스트로 정리할 기회가 있을것 같습니다.">01</a>]</sup></li>
<li>0부터 9까지의 숫자. 그러나 네이밍이 숫자로 시작할 수는 없습니다.</li>
<li>_ (언더바 또는 언더스코어), 그리고 $(달러) 기호의 단 두가지 특수기호.</li>
</ol>
<p>이렇게 세 종류를 네이밍에 사용할 수 있습니다. 상당히 심플하죠? 세번째 항목의 두 가지 특수기호 외에는 모두 연산자 또는 정규표현식에서 사용하도록 예약되어 있는 기호들이라 네이밍에는 사용할 수가 없습니다.</p>
<p style="text-align: center;">* * *</p>
<h3>변수의 네이밍 (캐멀 표기법)</h3>
<p>변수는 소문자로 시작하고 의미가 있는 단어를 구분하여 첫 글자만 대문자로 표현합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> myInstanceName<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span></pre></td></tr></table></div>

<p>위와 같은 형태입니다.<br />
위와 같이 소문자 기본에 단어를 기준으로 첫 글자를 대문자로 작성하는 표기법을 캐멀 표기법(Camel Notation 또는 Camel case)이라고 합니다. 네, 여러분이 떠올리신 그 낙타 맞습니다. 이런거죠. ^^</p>
<div id="attachment_416" class="wp-caption alignnone" style="width: 260px"><a href="http://en.wikipedia.org/wiki/Camel_case"><img class="size-full wp-image-416" title="250px-CamelCase.svg" src="http://ufx.kr/blog/wp-content/uploads/2010/05/250px-CamelCase.svg_.png" alt="" width="250" height="207" /></a><p class="wp-caption-text">위키백과의 Camel Case 에서 가져온 낙타 이미지</p></div>
<p>이 캐멀 표기법은 액션스크립트 코딩의 전반에 걸쳐 사용될 뿐만 아니라 거의 모든 객체지향 프로그래밍 언어들에서 사용하고 있는 방법이기도 합니다.</p>
<p>한편, 변수중에는 함수 내부에서 사용되는 지역 변수가 있을 수 있고 클래스 전체에서 사용되는 전역변수가 있죠?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #339966; font-weight: bold;">function</span> getHealthPoint<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span><span style="color: #000000;">&#123;</span>
	<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">value</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>; <span style="color: #009900;">// 함수 내부에서만 사용할 목적의 지역 변수를 생성하였습니다.</span>
	<span style="color: #004993;">value</span> = _hp <span style="color: #000000; font-weight: bold;">+</span> _itemBonus;
	<span style="color: #0033ff; font-weight: bold;">return</span> <span style="color: #004993;">value</span>;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>지역변수는 이렇게 함수 내부에서 잠깐 쓰이고 소멸시키는 변수이므로 간략하게 표현하는 경향이 있습니다. 함수가 길지 않은 경우라던가 무슨 의미인지 함수 바깥에서 굳이 알 필요가 없다면 더욱 간단하게 한글자 변수도 사용할 수 있습니다. 우리가 for 문에서 흔히 사용하는 i 나 j 같은 것이 그에 해당하겠죠.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> PlayCharacter<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">name</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>; <span style="color: #009900;">// public 변수명은 그냥 평범하게 사용합니다.</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _money<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span>; <span style="color: #009900;">// protected 와</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _hp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span>; <span style="color: #009900;">// private 에는 변수명 앞에 _ 가 붙어있습니다.</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>전역변수는 다시 public, protected, private, internal 네 가지로 나뉘지만 internal 은 거의 사용하지 않으므로 제외하고 위와 같이 세 가지의 접근제한자를 살펴보겠습니다.<br />
외부로 노출되는 public 전역변수는 가장 위에서 살펴본 것과 같이 일반적인 네이밍을 해 줍니다.<br />
private 는 이 클래스 내부에서만 사용할 수 있는 전역변수이므로 빠른 코드 힌팅을 위해 _ 언더바를 가장 처음에 붙여 네이밍 하는 경우가 많습니다. 우리는 이런 네이밍에 이미 익숙하죠? AS2.0 때부터 사용하던 네이밍 방식입니다. 물론 AS2.0 때는 언더바가 붙든 아니든 public 이었지만 말이죠.<br />
protected 는 상속 체인상에서만 사용할 수 있는 전역변수이므로 private 와 같은 스타일로 코딩하면 편리합니다.</p>
<p>이렇게 클래스의 private 변수에 언더바를 붙이는 방식은 사용하는 개발자도 있고, 그렇지 않은 개발자도 있습니다. 서로 의견이 다를 수는 있지만 이거 하나는 확실하죠. 코드 힌트를 받을 수 있는 에디터에서는 _ 를 타이핑 하는 순간 public 이 제외된 private, protected 멤버만 쫙~ 볼 수 있다는거!</p>
<div id="attachment_417" class="wp-caption alignnone" style="width: 369px"><img class="size-full wp-image-417" title="code_hint" src="http://ufx.kr/blog/wp-content/uploads/2010/05/code_hint.png" alt="" width="359" height="261" /><p class="wp-caption-text">FlashDevelop 에서의 코드 힌팅</p></div>
<p style="text-align: center;">* * *</p>
<h3>상수의 네이밍 (언더스코어 표기법)</h3>
<p>상수(const)는 변하지 않는 값입니다. 상수 생성과 함께 한번 설정한 값은 수정할 수 없습니다.<br />
변수는 var 키워드로 생성하지만, 상수는 const 키워드를 이용해 생성합니다.<br />
이러한 특성 때문에 상수는 변수와 확연히 구분되는 언더스코어 표기법(Underscore notation 또는 Underscore case)을 사용합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// MouseEvent 클래스의 상단에는 이와 같이 상수가 정의되어 있을 것입니다.</span>
static <span style="color: #0033ff; font-weight: bold;">public</span> const <span style="color: #004993;">ROLL_OVER</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span> = <span style="color: #990000;">&quot;rollOver&quot;</span>;</pre></td></tr></table></div>

<p>액션스크립트에서 상수를 표기할때 사용하는 언더스코어 표기법은 모든 문자열을 대문자로 작성하고 단어와 단어 사이는 언더바로 연결하는것이 일반적입니다.</p>
<p>* * *</p>
<h3>함수의 네이밍 (캐멀 표기법)</h3>
<p>함수의 네이밍은 기본적으로 변수의 규칙과 동일합니다. 생성자 함수 외에는 첫 글자를 소문자로 시작하고 언더바는 사용하지 않는것이 보통입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> PlayCharacter<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">name</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _money<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _hp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> PlayCharacter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 생성자 함수는 클래스의 이름과 동일해야 하기 때문에 예외적으로 첫 글자를 대문자로 사용합니다.</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> useWeapon<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span><span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 일반 함수의 네이밍</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p><span style="color: #99cc00;">함수는 보통 어떤 행동을 묘사</span>하는 경우가 많으므로 위의 예제코드 대로라면 &#8220;무기를사용&#8221; 한다라는 의미와 목적에 따라 단어를 조합해 사용하게 됩니다. 그리고 <span style="color: #99cc00;">영어의 어순에 따라 weaponUse 보다는 useWeapon 과 같이 동사+명사의 순서로 조합사용하는 것이 좀 더 일반적인 형태 입니다.</span><br />
물론 play() 와 같이 한 단어로 이루어진 함수명도 문제없습니다.<br />
그러나 단어가 명사라면? 그러니까 name 이라든지 age 같은 것이라면 이것은 속성이 되야하는 것은 아닌가 생각해 볼 필요가 있습니다.</p>
<p style="text-align: center;">* * *</p>
<h3>클래스의 네이밍 (파스칼 표기법)</h3>
<p>클래스는 대문자로 시작하고 나머지는 소문자로 작성하되, 의미가 다른 단어가 나오면 첫글자를 다시 대문자로 작성합니다. 캐멀 표기법과 동일하지만 네이밍의 첫 글자가 대문자로 표기하는 이 방법을 파스칼 표기법이라고 부릅니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> PlayCharacter<span style="color: #000000;">&#123;</span> <span style="color: #009900;">// 클래스명의 첫 문자는 대문자</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> PlayCharacter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 생성자 함수</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>간혹 코딩시작한지 얼마 안되는 초보분들이 클래스명을 소문자로 시작하거나 _ 언더바 기호를 단어 중간 사용하는 경우를 볼 수 있는데, 클래스의 대문자 시작 규칙과 특수기호를 사용하지 않는 규칙은 반드시 지켜주는 것이 좋습니다. 이 규칙이 깨질경우 변수, 함수와의 구분이 어려워지고 코드의 가독성이 떨어지게 됩니다.<br />
클래스명은 다른 한편으로는 데이터 형(type) 이죠. 우리가 var i:number 라고 하지 않고 var i:Number 라고 사용한다는 것을 기억하시기 바랍니다.</p>
<p style="text-align: center;">* * *</p>
<h3>인터페이스의 네이밍</h3>
<p>여러분이 인터페이스를 사용할 정도라면 표기법 정도는 이미 알고 계실테지만, 빠짐없이 모두 짚고 넘어가보자는 취지를 살려보겠습니다.</p>
<p>인터페이스 역시 클래스와 마찬가지로 데이터형(type)이 될 수 있고, 상속과 비슷한 implements (구현)을 통해 클래스를 확장하는 기능을 합니다.<br />
인터페이스를 메소드 상속이라고 부르는 사람도 있죠? 상속과 비슷하지만 메서드를 구현하는것을 강제하기 때문인데요. 메서드가 기본적으로 동사형태를 띄고 있으므로 메서드를 강제한다, 또는 사용할 수 있다는 의미로 &#8220;~를 할 수 있는&#8221; 의 의미를 가진 able 을 접미사로 붙이게 됩니다.<sup>[<a href="http://ufx.kr/blog/414#footnote_1_414" id="identifier_1_414" class="footnote-link footnote-identifier-link" title="Observer 패턴의 인터페이스로 able을 붙여 Observerable 이라고 네이밍 하는 식입니다.">02</a>]</sup><br />
Java 인터페이스 역시 -able 을 붙이는 스타일이 일반적이고, 액션스크립트가 Java 로부터 많은 부분의 기원을 두고 있으므로 액션스크립트도 그런 스타일을 따르기도 합니다만, 액션스크립트는 그보다는 우리가 흔히 볼 수 있는 IEventDispatcher 에서 처럼 인터페이스 가장 첫 글자 앞에 대문자 I 를 붙이는 방법을 더 많이 사용합니다.<br />
물론 IObserverble 과 같이 두 가지 방법을 모두 적용해도 무방합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span><span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> interface IAttackable<span style="color: #000000;">&#123;</span>
		<span style="color: #339966; font-weight: bold;">function</span> attack<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span>Damage
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이런식이 되겠네요.</p>
<p style="text-align: center;">* * *</p>
<h3>그리고 단어 줄임 또는 단어 이니셜 사용</h3>
<p>위에서 소개한 네이밍 규칙들을 모두 적용해보면, 변수나 함수의 길이가 길어지게 됩니다만,<sup>[<a href="http://ufx.kr/blog/414#footnote_2_414" id="identifier_2_414" class="footnote-link footnote-identifier-link" title="상하로 늘어나진 않겠죠. 좌우로 늘어납니다.">03</a>]</sup> 그렇다고 해서 단어를 약어나 이니셜을 과도하게 사용하게 되면 코드의 가독성이 떨어지게 됩니다.<br />
&#8220;어차피 다른사람이 볼 코드도 아닌데 뭐&#8221; 라는 생각을 하고 계실지라도 말이죠. 정작 본인조차도 2주 후에는 알아볼 수 없는 코드가 되버립니다. 유지보수 효율성은 저 달나라로 가고 있습니다.<br />
btn (button), mc (MovieClip), cfg (config), init (initialize)  같은 수준은 괜찮습니다. 줄인 단어일지라도 자주 사용되고 누가봐도 대부분 뜻이 통하면 사용에 지장이 생기지 않습니다.</p>
<p>무엇보다 과도하게 길어지지 않는 한도내에서 옆사람도 이해할 수 있도록 쉬운 영어로 풀어서 묘사적으로 네이밍 하는것이 기본이라 할 수 있습니다. 학교다닐때 영어공부를 열심히 하지 않으신 분은 인터넷 영어사전 하나 쯤 펼쳐놓고 코딩하는 자세가 좋을것 같습니다.</p>
<ol class="footnotes"><li id="footnote_0_414" class="footnote">물론 액션스크립트는 uft-8 로 인코딩을 하므로 한글을 포함한 모든 언어의 문자열을 사용할 수 있으나 여러 가지 문제가 생길 수 있는 여지가 있으므로 영문 문자열로 네이밍을 제한하는 것이 좋습니다. 이에 해당하는 내용은 차후 별도의 포스트로 정리할 기회가 있을것 같습니다.</li><li id="footnote_1_414" class="footnote">Observer 패턴의 인터페이스로 able을 붙여 Observerable 이라고 네이밍 하는 식입니다.</li><li id="footnote_2_414" class="footnote">상하로 늘어나진 않겠죠. 좌우로 늘어납니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/414/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>AS3.0 클래스의 상속(extends)구조에서 상위, 하위 클래스의 메서드 호출방법</title>
		<link>http://ufx.kr/blog/407</link>
		<comments>http://ufx.kr/blog/407#comments</comments>
		<pubDate>Fri, 02 Apr 2010 14:50:07 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[extends]]></category>
		<category><![CDATA[override]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[상속]]></category>
		<category><![CDATA[클래스]]></category>
		<category><![CDATA[확장]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=407</guid>
		<description><![CDATA[자, 여기서는 부모 객체, 자식 객체가 아닌 상위 클래스, 하위 클래스로 제목을 잡았습니다. &#8220;부모 클래스, 자식 클래스로 표현해도 되는것 아니야?&#8221; 하는 의문을 가진 분들이 계실것 같습니다만, 적절하지 않습니다. 부모 클래스가 아닌 상위 클래스 또는 수퍼 클래스(super class)로, 자식 클래스가 아닌 하위 클래스 또는 서브 클래스(sub class)로 말해야 합니다. 클래스와 객체는 엄연히 다르죠. 클래스는 설계도일 뿐 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-408" title="inheritance" src="http://ufx.kr/blog/wp-content/uploads/2010/04/inheritance.gif" alt="" width="122" height="240" />자, 여기서는 부모 객체, 자식 객체가 아닌 상위 클래스, 하위 클래스로 제목을 잡았습니다. &#8220;부모 클래스, 자식 클래스로 표현해도 되는것 아니야?&#8221; 하는 의문을 가진 분들이 계실것 같습니다만, 적절하지 않습니다. 부모 클래스가 아닌 상위 클래스 또는 수퍼 클래스(super class)로, 자식 클래스가 아닌 하위 클래스 또는 서브 클래스(sub class)로 말해야 합니다.</p>
<p>클래스와 객체는 엄연히 다르죠. 클래스는 설계도일 뿐 입니다. 이 설계도(Class)를 이용해서 무언가를 만들면, 그것이 바로 객체(Object) 입니다. 그러므로 상위 클래스든 하위 클래스든 상속 체인과는 상관없이 이 설계도를 가지고는 부모 객체를 만들수도 있고 자식 객체를 만들수도 있죠. 이 당연한 사실을 이제 막 액션스크립트에 입문한 초보 개발자들은 깨닫지 못하는 경우가 많습니다.</p>
<p>실제 예를 들어보면 명확해집니다. DisplayObject 구조 상속 체인상으로 MovieClip 은 Sprite 를 상속했지만, 실제 우리는 MovieClip 클래스로 만든 객체를 부모 객체로, Sprite 클래스로 만든 객체를 자식 객체로 만들수 있는것과 같습니다.</p>
<p>어쨌든 부모, 자식 부모, 자식이라는 용어가 객체에서 사용되는것처럼 클래스에서 사용되는 경우가 있기 때문에 초보 분들이 혼동을 일으키는 것입니다. 여기서는 혼동을 줄이기 위해 상위 클래스, 하위 클래스로 지칭하겠습니다.<br />
<span id="more-407"></span></p>
<h3>A. 상속한 경우 하위 클래스가 상위 클래스의 멤버를 사용</h3>
<p>하위 클래스에서 상위 클래스의 메서드나 변수를 사용하고 싶으면, 그냥 사용하면 되죠. 단, public 이나 protected 인 녀석들에 한정해서 입니다. 하위 클래스는 상위 클래스를 확장(extends 키워드를 사용합니다.)한 것이므로, 이런 상태에서 객체를 만들면 extends 한 클래스의 멤버를 하위클래스에서 이미 사용가능하도록 상위 클래스와 하위 클래스는 이미 합체 되어 있다고 보면 됩니다. (물론 private 는 제외)<br />
그러므로 다들 잘 아시는 바와 같이 하위 클래스에서는 상위 클래스의 public 이나 protected 멤버를 그냥 사용할 수 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;SuperClass 에서 실행된 doSomething()&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>하위 클래스의 클래스 정의 라인을 주의해서 보세요. extends SuperClass 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SubClass extends SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> SubClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// SuperClass 의 protected 메서드 호출가능</span>
			doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h3>B. 상속한 경우 상위 클래스가 하위 클래스의 메서드를 호출</h3>
<p>그런데 그 반대의 경우는 어떤가요? 상위 클래스의 입장에서 보면 자신을 상속(확장)하게될 하위 클래스가 어떤 것이 될지 알 수 없으므로 하위 클래스의 메서드나 변수등을 알 수 있는 방법이 없습니다. 호출이 불가능한 경우의 예를 보면 이해가 빠를것 같습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> SuperClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 호출 불가 !!</span>
			doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>SuperClass 를 상속한 SubClass 의 doSomething() 메서드를 SuperClass 에서 호출하는 것은 불가능 합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SubClass extends SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;SubClass 에서 실행된 doSomething()&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<div id="attachment_409" class="wp-caption alignleft" style="width: 190px"><img class="size-full wp-image-409 " title="override" src="http://ufx.kr/blog/wp-content/uploads/2010/04/override.jpg" alt="" width="180" height="141" /><p class="wp-caption-text">덮어쓰세요!!</p></div>
<p>그래서 이런 경우, 하위 클래스에서 호출하고 싶은 메서드를 상위 클래스에 public 또는 protected 으로 만들어 놓고, 하위 클래스에서는 override 를 사용하여 같은 이름으로 메서드를 재정의 하면, 상위 클래스의 메서드 본문은 무시되고, 하위 클래스의 메서드를 호출하는 효과를 가질 수 있습니다.<br />
override 를 사용할 때 메서드 정의 부분은 인자와 반환 타입까지 모두 완전히 동일해야 하지 않으면 컴파일 타임에 에러를 내므로, 메서드 본문과 override 키워드의 추가 외에는 모든 내용이 동일해야 합니다.</p>
<p>아래의 코드는 개선된 상위 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SuperClass
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> SuperClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">throw</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Error</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;이런 이런~ doSomething() 메서드를 override 하는걸 까먹었군요!!&quot;</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>SuperClass 에 doSomething() 이 정의되어 있으므로 SuperClass 에서 doSomething() 메서드가 호출이 가능해 집니다. 그러나 실제로 실행 되는 메서드는 SubClass 에 있는 doSomething() 메서드 입니다.<br />
아래는 상위 클래스를 상속한 개선된 하위 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> SubClass extends SuperClass
	<span style="color: #000000;">&#123;</span>
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;SubClass 에서 호출된 doSomething()&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이런 경우에 SubClass 의 doSomething() 메서드에 대한 상대적인 개념으로 SuperClass 에 있는 doSomething() 메서드를 추상 메서드 라고 할 수 있습니다. Java 의 abstract 키워드 같이 명시적으로 추상 메서드를 지원하는 것은 아니지만 위에 보는 바와 같이 메서드 바디 부분에 new Error 를 throw 해 놓음으로써 SubClass 에서 해당 메서드를 강제로 override 하게 만드는 기능을 대신하는 것이죠. SubClass 에서 override 하지 않으면 컴파일 에러가 발생합니다.</p>
<p><span style="color: #5d5aa5;">그냥 SubClass 형(type)에서 doSomething() 메서드를 사용하면 되지 않겠냐&#8230; 하시겠지만, 아래와 같은 이유를 고려할 필요가 있습니다.</span></p>
<ol>
<li>가능하면 상위 형(type)으로 객체를 핸들링 하는 것이 유리합니다.<br />
<span style="color: #808080;">이 내용은 참으로 많은 의미를 가지고 있습니다만, 주제를 살짝 벗어나는 내용이므로 일단 이렇게만 알고 넘어가고 자세한 것은 차차 알아가도록 하죠.</span></li>
<li>throw new Error() 를 해 놓지 않으면 SuperClass 에서 SubClass 에게 doSomething() 메서드를 강제할 방법이 없어집니다.<br />
<span style="color: #808080;">doSomething() 메서드는 반드시 구현되어야 할 메서드지만, SuperClass 에서 throw new Error() 해 놓지 않으면 doSomething() 메서드를 구현하는 것을 잊을 가능성이 생깁니다. &#8220;설마&#8230;&#8221; 하실지도 모르겠지만, 다른 개발자가 하위 클래스를 구현하는 경우라던가, 심지어는 자신이 SuperClass 를 만들었어도 일주일만 지나면 까맣게 잊는 경우가 허다합니다. override 를 하지 않은 상태에서 컴파일을 하면 아래 그림과 같이 컴파일러 또는 Flash Player가 친절하게도 에러를 발생해 주므로 쉽게 오류를 바로잡을 수 있게 되는거죠.</span></li>
</ol>
<div id="attachment_410" class="wp-caption aligncenter" style="width: 567px"><img class="size-full wp-image-410 " title="throw_new_Error" src="http://ufx.kr/blog/wp-content/uploads/2010/04/throw_new_Error.png" alt="" width="557" height="230" /><p class="wp-caption-text">마땅히 override 해야할 하위 클래스에서 임무를 망각했을 때 Flash Player 가 보여주는 런타임 에러</p></div>
<p style="text-align: center;">* * *</p>
<p>그렇지만 위와같이 예제를 봐도 뜬구름 잡는 느낌일뿐 뭔가 잘 와닿지 않죠? 자 그럼 override 한 메서드를 이용하는 실제에 가까운 예를 보도록 합니다.</p>
<p>아래는 상위 클래스에 해당하는 추상층 Item 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.filters</span>.<span style="color: #004993;">BitmapFilter</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> Item extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _filterList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #6699cc; font-weight: bold;">var</span> _filter<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">BitmapFilter</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> Item<span style="color: #000000;">&#40;</span> $color<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect 그리기</span>
			<span style="color: #009900;">// 그림 그리기, 이벤트리스너는 공통이므로 상위 클래스에서 처리</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> $color <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">ROLL_OVER</span>, rollOverHandler <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">ROLL_OUT</span>, rollOutHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> rollOverHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 공통적인 로직은 상위 클래스에서 처리.</span>
			<span style="color: #004993;">filters</span> = _filterList;
&nbsp;
			<span style="color: #009900;">// 개별적인 로직을 처리하기 위한 메서드를 실행.</span>
			rollOverForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #009900;">// 이렇게 이 객체를 addChild 한 부모 객체가 수신할 수 있도록 dispatchEvent() 하면서</span>
			<span style="color: #009900;">// 커스텀 이벤트를 이용해 이 Item 객체 내부에 있는 필터 객체를 보냄</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">dispatchEvent</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">new</span> CustomEvent<span style="color: #000000;">&#40;</span> CustomEvent.CALL, <span style="color: #000000;">&#123;</span> filterObject<span style="color: #000000; font-weight: bold;">:</span> <span style="color: #0033ff; font-weight: bold;">this</span>._filter <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> rollOutHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">filters</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
			rollOutForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 하위 클래스 에서 override 해야 하는 메서드.
		 * protected 로 선언되어 있음
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOverForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">throw</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Error</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;이런 이런~ addFilter() 메서드를 override 하는걸 까먹었군요!!&quot;</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOutForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">throw</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Error</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;이런 이런~ removeFilter() 메서드를 override 하는걸 까먹었군요!!&quot;</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>마우스 롤 오버 인터랙션에 사용한 커스텀 이벤트 클래스는, 포스트 본문 가장 아래쪽 소스코드 다운로드에 포함되어 있습니다.</p>
<p>아래는 위의 Item 클래스를 상속한 하위 클래스인 GlowItem 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.filters</span>.<span style="color: #004993;">BlurFilter</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.filters</span>.<span style="color: #004993;">GlowFilter</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> GlowItem extends Item
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _rollOutFilterList<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Array</span> = <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _blurFilter<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">BlurFilter</span>;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> GlowItem<span style="color: #000000;">&#40;</span> $color<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">super</span><span style="color: #000000;">&#40;</span> $color <span style="color: #000000;">&#41;</span>;
			_filter = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">GlowFilter</span><span style="color: #000000;">&#40;</span> 0x6699FF, <span style="color: #000000; font-weight:bold;">1</span>, <span style="color: #000000; font-weight:bold;">20</span>, <span style="color: #000000; font-weight:bold;">20</span> <span style="color: #000000;">&#41;</span>;
			_filterList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> _filter <span style="color: #000000;">&#41;</span>;
&nbsp;
			_blurFilter = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">BlurFilter</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">20</span>, <span style="color: #000000; font-weight:bold;">0</span> <span style="color: #000000;">&#41;</span>;
			_rollOutFilterList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> _blurFilter <span style="color: #000000;">&#41;</span>;
			rollOutForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOverForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 여긴 딱히 할일이 없군요.</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOutForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 이 클래스는 롤아웃 상태에서 블러 필터를 적용한다는 설정</span>
			<span style="color: #004993;">filters</span> = _rollOutFilterList;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>아래는 Item 클래스를 상속한 하위 클래스인 DropShadowItem 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.filters</span>.<span style="color: #004993;">DropShadowFilter</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> DropShadowItem extends Item
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> DropShadowItem<span style="color: #000000;">&#40;</span> $color<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">uint</span> <span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">super</span><span style="color: #000000;">&#40;</span> $color <span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">alpha</span> = <span style="color: #000000; font-weight:bold;">0.5</span>;
			_filter = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">DropShadowFilter</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">5</span>, <span style="color: #000000; font-weight:bold;">45</span>, 0x000000, <span style="color: #000000; font-weight:bold;">0.7</span>, <span style="color: #000000; font-weight:bold;">5</span>, <span style="color: #000000; font-weight:bold;">5</span> <span style="color: #000000;">&#41;</span>;
			_filterList.<span style="color: #004993;">push</span><span style="color: #000000;">&#40;</span> _filter <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOverForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 이 클래스는 GlowItem 클래스와는 달리 alpha 속성을 함께 변경한다는 설정</span>
			<span style="color: #004993;">alpha</span> = <span style="color: #000000; font-weight:bold;">1</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		override <span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> rollOutForm<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">alpha</span> = <span style="color: #000000; font-weight:bold;">0.5</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>여기까지는 하나의 Item 상위 클래스에 두 가지 형태로 하위 클래스를 만들었습니다. 클래스 다이어 그램으로 보면 좀더 한눈에 이해하기 쉬울것 같습니다.<br />
<img class="aligncenter size-full wp-image-411" title="diagram" src="http://ufx.kr/blog/wp-content/uploads/2010/04/diagram.png" alt="" width="430" height="316" /></p>
<p>그리고 아래는 도큐먼트 클래스 입니다. 두 종류의 하위 클래스로 각각 한개씩의 객체를 생성했습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #000000;">&#91;</span>SWF <span style="color: #000000;">&#40;</span> <span style="color: #004993;">width</span> = <span style="color: #000000; font-weight:bold;">440</span>, <span style="color: #004993;">height</span> = <span style="color: #000000; font-weight:bold;">160</span>, <span style="color: #004993;">frameRate</span> = <span style="color: #000000; font-weight:bold;">30</span>, <span style="color: #004993;">backgroundColor</span> = 0xE3E3E3 <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#93;</span>
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> DocumentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> DocumentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> item1<span style="color: #000000; font-weight: bold;">:</span>Item = <span style="color: #0033ff; font-weight: bold;">new</span> GlowItem<span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">with</span> <span style="color: #000000;">&#40;</span> <span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item1 <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;item1&quot;</span>;
				<span style="color: #004993;">x</span> = <span style="color: #000000; font-weight:bold;">100</span>;
				<span style="color: #004993;">y</span> = <span style="color: #000000; font-weight:bold;">30</span>;
				<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> CustomEvent.CALL, callHandler <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
&nbsp;
			<span style="color: #6699cc; font-weight: bold;">var</span> item2<span style="color: #000000; font-weight: bold;">:</span>Item = <span style="color: #0033ff; font-weight: bold;">new</span> DropShadowItem<span style="color: #000000;">&#40;</span> 0x008FCC <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">with</span> <span style="color: #000000;">&#40;</span> <span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> item2 <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #004993;">name</span> = <span style="color: #990000;">&quot;item2&quot;</span>;
				<span style="color: #004993;">x</span> = <span style="color: #000000; font-weight:bold;">240</span>;
				<span style="color: #004993;">y</span> = <span style="color: #000000; font-weight:bold;">30</span>;
				<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> CustomEvent.CALL, callHandler <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> callHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span>CustomEvent <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> $e.<span style="color: #004993;">currentTarget</span>.<span style="color: #004993;">name</span>, <span style="color: #990000;">&quot;filterObject:&quot;</span>, $e.<span style="color: #004993;">data</span>.filterObject <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>이 도큐먼트 클래스를 컴파일 하면 아래와 같은 swf 파일이 됩니다. 각각의 아이콘에 마우스를 올려보세요.</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="440" height="160" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="align" value="middle" /><param name="quality" value="high" /><param name="src" value="http://ufx.kr/blog/wp-content/uploads/2010/04/DocumentClass.swf" /><embed type="application/x-shockwave-flash" width="440" height="160" src="http://ufx.kr/blog/wp-content/uploads/2010/04/DocumentClass.swf" quality="high" align="middle"></embed></object></p>
<p>마우스 롤 오버에 필터를 적용하여 공통적으로 처리하는 부분은 상위 클래스에서 처리하게 되고, 공통적이지 않은 부분, 즉 GlowItem 의 경우 롤 아웃 상황에서 Blur 필터를 적용하는 것과, DropShadowItem 의 경우 alpha 속성을 변경하는 것을, 각각의 클래스에서 처리하게 하는 방법을 표현해 봤습니다.</p>
<p><span style="color: #5d5aa5;">메서드의 호출은 모두 상위 클래스인 Item 클래스에서 일어나게 되고, 하위 클래스에서는 각각의 상황에 맞는 상태를 상위 클래스에 공급해 놓는 역할을 한 것입니다.</span></p>
<a href="http://ufx.kr/blog/wp-content/plugins/download-monitor/download.php?id=23" title="Downloaded 378 times"><img src="http://ufx.kr/blog/wp-content/uploads/2009/07/zip_icon.gif" />&nbsp; override 예제 코드 다운로드</a> - DocumentClass.as, Item.as, GlowItem.as, DropShadowItem.as, CustomEvent.as, 그리고 컴파일된 DocumentClass.swf
<p style="text-align: center;">* * *</p>
<p>이렇게 클래스의 상속 구조에서 상,하위 클래스간 메서드의 호출 방법을 알아보았습니다. 이와는 다르게 객체간 통신 방법에 대해 궁금하신 분들은, 지난 포스트 &#8220;<a href="./404">AS3.0 클래스 구조의 여러가지 상황에서 부모, 자식 객체의 참조 방법</a>&#8221; 을 읽어 보시기 바랍니다. </p>
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/407/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>AS3.0 클래스 구조의 여러가지 상황에서 부모, 자식 객체의 참조 방법</title>
		<link>http://ufx.kr/blog/404</link>
		<comments>http://ufx.kr/blog/404#comments</comments>
		<pubDate>Mon, 29 Mar 2010 09:35:02 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[addEventListener]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[dispat]]></category>
		<category><![CDATA[dispatchEvent]]></category>
		<category><![CDATA[DisplayObject]]></category>
		<category><![CDATA[DisplayObjectContainer]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[EventDispatcher]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[고수들는 가르쳐주지 않아요]]></category>
		<category><![CDATA[무비클립]]></category>
		<category><![CDATA[이벤트]]></category>
		<category><![CDATA[참조]]></category>
		<category><![CDATA[통신]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=404</guid>
		<description><![CDATA[fla 파일의 프레임에 코드를 잔뜩 늘어놓았던 시절에는, 모든 함수와 변수의 스코프가 동일하므로 참조하는 방법에 대한 고민을 거의 하지 않아도 좋았습니다. 말하자면 fla 프레임의 코드는 하나의 클래스이면서, 생성자 함수외에는 존재하지 않는 클래스라고 볼 수 있을겁니다. 그러나 클래스를 이용하여 객체를 생성하는 경우에는 그렇게 단순하게만 돌아가지는 않습니다. 필연적으로, 원하지 않아도 부모 객체와 자식 객체를 생성하게 되는데, 몇 가지 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-406" title="hidden_object" src="http://ufx.kr/blog/wp-content/uploads/2010/03/hidden_object.jpg" alt="" width="300" height="200" />fla 파일의 프레임에 코드를 잔뜩 늘어놓았던 시절에는, 모든 함수와 변수의 스코프가 동일하므로 참조하는 방법에 대한 고민을 거의 하지 않아도 좋았습니다. 말하자면 fla 프레임의 코드는 하나의 클래스이면서, 생성자 함수외에는 존재하지 않는 클래스라고 볼 수 있을겁니다.</p>
<p>그러나 클래스를 이용하여 객체를 생성하는 경우에는 그렇게 단순하게만 돌아가지는 않습니다. 필연적으로, 원하지 않아도 부모 객체와 자식 객체를 생성하게 되는데, 몇 가지 규칙을 알고 있어야만 올바른 객체간 통신을 할 수 있게 됩니다.</p>
<p>이 내용은 AS2.0을 다루던 초보 개발자들이 AS3.0에 와서 가장 먼저 부딪히는 부분이며, 가장 많이 헤메는 부분이기도 합니다. 이제까지 MovieClip 이나 Sprite 객체를 만들어 마우스 클릭 이벤트만 걸고 노는 것에만 익숙했던 분들은 이 포스트를 정독하시면 많은 것을 얻으실 수 있을겁니다. 그런 즉슨 이 포스트는 AS3.0 에 막 입문한 초보분들을 위한 포스트 입니다.</p>
<p>아래에 설명한 방법들은 객체간 통신을 하기 위해 사용하는 여러가지 방법들 입니다. 물론 이 외에도 다른 방법이 있을 수 있습니다만, 가장 사용빈도가 높고 반드시 알아야 하는 몇 가지 방법을 소개하겠습니다.</p>
<p><span id="more-404"></span></p>
<h3>A. 부모 객체가 자식 객체를 참조</h3>
<p>객체간 관계에서 가장 흔한 상황이 되겠습니다. 부모 객체는 다수의 자식 객체를 가질 수 있고, 자식 객체에 public 으로 선언된 변수나 함수에 대해서는 자식 객체의 객체이름을 통하여 참조할 수 있다는것을 모두들 잘 알고 계실겁니다. 코드로 보면 아래와 같죠.<br />
아래는 부모 객체를 생성한 부모 클래스의 코드 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> _childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> _childInstance <span style="color: #000000;">&#41;</span>;
			_childInstance.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>아래는 자식 객체를 생성한 자식 클래스의 코드 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;하위 클래스 : do something in ChildClass !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h3>B. 자식 객체가 부모 객체를 참조 &#8211; 첫 번째 방법</h3>
<p>자, 그럼 거꾸로 자식 객체가 부모 객체에 있는 함수나 변수를 참조하려면 어떻게 하면 될까요? 자식 객체에서 parent 키워드를 사용하면 자신을 addChild 한 부모에게 접근할 수 있습니다만, DisplayObject 상속구조상의 메서드, 속성만 사용 가능할뿐 부모 객체에 정의된 것을 사용할 수는 없습니다.<br />
이것의 논리적 원인을 따져보자면 이렇습니다. 우리가 부모, 자식 객체를 맺어주는데 사용한 메서드는 addChild() 입니다. addChild() 메서드는 Sprite 클래스가 바로 윗 단계에서 상속한 DisplayObjectContainer 클래스의 메서드죠. 아래의 레퍼런스 스샷에서 보시는 바와 같이 parent 를 사용해도 반환되어 나오는 것은 DisplayObjectContainer 입니다.</p>
<div id="attachment_405" class="wp-caption alignnone" style="width: 610px"><a href="http://help.adobe.com/ko_KR/AS3LCR/Flash_10.0/flash/display/DisplayObjectContainer.html"><img class="size-full wp-image-405" title="DisplayObjectContainer_parent" src="http://ufx.kr/blog/wp-content/uploads/2010/03/DisplayObjectContainer_parent.png" alt="" width="600" height="146" /></a><p class="wp-caption-text">DisplayObjectContainer 의 읽기 전용 속성인 parent. 반환되어 나오는 것도 DisplayObjectContainer.</p></div>
<p>다시말해, DisplayObject 상속 체인 구조<sup>[<a href="http://ufx.kr/blog/404#footnote_0_404" id="identifier_0_404" class="footnote-link footnote-identifier-link" title="Object &amp;#8211; EventDispatcher &amp;#8211; DisplayObject &amp;#8211; InteractiveObject &amp;#8211; DisplayObjectContainer &amp;#8211; Sprite">01</a>]</sup> 에서 부모와 자식 객체간의 결합은 DisplayObjectContainer 가 담당하고 있다는 것이죠&#8230; 라는 내용은 당연스러운 사실이지만, 무심코 사용한 parent 역시 DisplayObjectContainer 형(type)을 반환 하므로, DisplayObjectContainer 를 상속한 Sprite 도, 그 Sprite 를 상속한 개별 클래스(ParentClass) 역시 DisplayObjectContainer 까지의 메서드, 속성만 사용할 수 있습니다.<sup>[<a href="http://ufx.kr/blog/404#footnote_1_404" id="identifier_1_404" class="footnote-link footnote-identifier-link" title="Object, EventDispatcher, DisplayObject, InteractiveObject,  DisplayObjectContainer 의 메서드, 속성만 사용할 수 있고, Sprite 이하의 메서드, 속성은 사용할 수 없습니다.">02</a>]</sup><br />
약간 어려운가요? 논리적 원인을 따지자니 오히려 어려워진 감이 있는데, 어쨌건 ParentClass 의 메서드나 속성을 사용하기 위해서는 ParentClass로 형 변환을 해줘야 한다는 것만 이해하고 있다면 오케이 입니다.</p>
<p>아래는 부모 객체를 만드는데 사용한 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> childInstance <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;상위 클래스 : do something in ParentClass !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>아래는 자식 객체를 만드는데 사용한 클래스 입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, clickHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> clickHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">parent</span> <span style="color: #000000;">&#41;</span>; <span style="color: #009900;">// 출력 : [object ParentClass]</span>
&nbsp;
			<span style="color: #009900;">// this.parent 는 DisplayObject 구조의 메서드나 속성만을 사용할 수 있음.</span>
			<span style="color: #009900;">// 상위 클래스 형(type)으로 형변환(casting:캐스팅) 하면 public 멤버를 사용할 수 있음</span>
			ParentClass<span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">parent</span> <span style="color: #000000;">&#41;</span>.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #009900;">// 아래는 컴파일 에러</span>
			<span style="color: #009900;">// this.parent.doSomething();</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>trace( this.parent ) 출력 결과에서 보는것과 같이 parent 는 확실히 부모 객체 자체 까지는 참조 가능하지만 parent 가 가리키고 있는 것은 부모 객체의 DisplayObjectContainer 형태이기 때문에 부모 객체의 doSomething() 을 호출하게 되면 컴파일 에러가 발생합니다.<br />
그래서 위와 같이 ParentClass로 형변환을 해야 부모 객체의 메서드를 사용할 수가 있습니다.</p>
<p>또한 형변환은 아래와 같이 할 수도 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> parentInstance<span style="color: #000000; font-weight: bold;">:</span>ParentClass = <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">parent</span> <span style="color: #0033ff; font-weight: bold;">as</span> ParentClass;
parentInstance.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<h3>C. 자식 객체가 부모 객체를 참조 &#8211; 두 번째 방법</h3>
<p>자식 객체에서 부모 객체의 public 메서드를 사용하는 방법은 B 케이스와 같이 형변환 하는 방법 외에도 한가지 더 있습니다. 부모객체가 자식객체에게 부모 객체 자신을 참조할 수 있는 참조(레퍼런스)를 넘겨주는 방법입니다. 아래와 같이 말이죠.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> childInstance <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #009900;">// 이렇게 자식 객체에게 this(부모 자신의 객체 레퍼런스)를 넘겨줌</span>
			childInstance.updateParent<span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;상위 클래스 : do something in ParentClass !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _parent<span style="color: #000000; font-weight: bold;">:</span>ParentClass;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, clickHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #3f5fbf;">/**
		 * 부모 객체의 레퍼런스를 저장함 (부모 객체에서 호출)
		 * @param	부모객체를 인자로 받아 전역변수에 저장
		 */</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> updateParent<span style="color: #000000;">&#40;</span> $parent<span style="color: #000000; font-weight: bold;">:</span>ParentClass <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>._parent = $parent;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> clickHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>._parent.doSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>마치&#8230;부모가 통장과 도장과 비밀번호를 자식에게 알려주는 것과 같은 느낌이네요.</p>
<h3>D. 자식 객체가 부모 객체에게 이벤트를 보냄</h3>
<p>위의 B, C 케이스를 이벤트로 통신을 하는 형태로 바꿔보면 어떨까요? 흔히 사용하는 MouseEvent 도 이에 해당하지만, MouseEvent 같이 사용자의 인터랙션에 의한 이벤트는, 이벤트를 발생하는 객체(dispatcher:디스패쳐)가 하는일이 없는것처럼 보이므로 아래와 같이 일부러 디스패쳐를 사용하는 상황을 구성해보았습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #6699cc; font-weight: bold;">var</span> childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> childInstance <span style="color: #000000;">&#41;</span>;
			childInstance.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">COMPLETE</span>, animationComplete <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> animationComplete<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Event</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;부모 객체에서 자식 객체에 걸어놓은 Event.COMPLETE 를 캐치함 !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>자식 객체를 만든 클래스 입니다. 클릭을 하게 되면 객체 자신에게 Event.ENTER_FRAME 을 걸게 되고 매 프레임마다 enterFrameHandler() 핸들러를 실행하게 됩니다. 자세한 내용은 주석을 참고하세요.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, clickHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> clickHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">ENTER_FRAME</span>, enterFrameHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> enterFrameHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Event</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// x 가 200이 될 때까지 감속운동 (easeOut)</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">x</span> <span style="color: #000000; font-weight: bold;">+</span>= <span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">200</span> <span style="color: #000000; font-weight: bold;">-</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">x</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight:bold;">0.1</span>;
&nbsp;
			<span style="color: #009900;">// 200이 되면 엔터프레임을 중단하고 Event.COMPLETE 를 dispatchEvent() 함</span>
			<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span> <span style="color: #004993;">Math</span>.<span style="color: #004993;">round</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">x</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000; font-weight: bold;">&gt;</span>= <span style="color: #000000; font-weight:bold;">200</span> <span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">removeEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">ENTER_FRAME</span>, enterFrameHandler <span style="color: #000000;">&#41;</span>;
				<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">dispatchEvent</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Event</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">COMPLETE</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>;
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>실제 작업에서는 이런 종류의 코드를 작성해야 하는 경우가 많을 겁니다. 자식 객체에서 발생한 어떤 상황을 모두 실행한 후, 그 결과를 부모에게 알리고 싶은거죠.</p>
<h3>E. 부모 객체가 자식 객체에게 이벤트를 보냄</h3>
<p>부모 객체가 자식 객체에게 이벤트를 보낼 경우도 있겠죠? 부모 객체 입장에서는 자식 객체의 public 멤버들은 모두 참조가 가능하므로 자식 객체의 메서드나 변수를 직접 참조하여 데이터를 전달하거나 메서드를 호출할수도 있습니다. 바로 A케이스와 같은거죠.<br />
그러나 A 케이스의 경우 부모 객체가 자식객체의 public 멤버들이 뭔지 알고 있어야 합니다. 물론 Flash(Flex) Builder 나 FlashDevelop, 또는 FDT, 그리고 Flash CS5 같이 코드 힌트를 지원하는 에디터에서는 자식객체가 가지고 있는 public 멤버들을 볼 수 있지만, 여기서 말하는 것은 그런 기능적인 부분을 이야기 하는 것이 아니라 객체지향 프로그래밍에서의 설계 원칙의 문제입니다. 예를 들어보죠.</p>
<p>만약 부모 객체와 자식 객체가 서로 분리되야할 상황이 생겼습니다. A나 B 케이스는 부모 자식객체간에 서로 직접 참조하고 있으므로, 이 두 객체를 만든 클래스가 분리되는 순간 서로를 참조하고 있던 부분은 모두 컴파일 에러가 발생합니다. 이런 것을 보고 두 객체간 강한 결합을 했다고 표현하죠.<br />
한편, D나 E 케이스는 이벤트를 통해 이 결합을 다소 약하게 만들 수 있습니다. 데이터를 이벤트를 통해 전달하고 이벤트를 보냈다고 어떤 행동을 강제하지 않습니다. 이벤트를 보내는 입장에서는 보내는 걸로 역할을 다 한 것이고 받는 입장에서는 받긴 받았지만 이것을 실행할지 말지는 자신이 결정할 수 있기 때문입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _roundRect<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect</span>
			_roundRect.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x996633 <span style="color: #000000;">&#41;</span>;
			_roundRect.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			_roundRect.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			_roundRect.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, clickHandler <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> _roundRect <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> _childInstance <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> clickHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// _roundRect 의 MouseEvent.CLICK 를 캐치하면</span>
			<span style="color: #009900;">// _childInstance 객체에 MouseEvent.ROLL_OUT 이벤트를 보냄</span>
			_childInstance.<span style="color: #004993;">dispatchEvent</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">MouseEvent</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">ROLL_OUT</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>부모 객체에서 사용자의 인터랙션에 의해 발생한 MouseEvent.CLICK과는 다른 이벤트를 고르느라 자식 객체에는 MouseEvent.ROLL_OUT 를 보내는 다소 엉뚱한 예제 입니다만, 이벤트는 이렇게도 할 수 있다는것을 보여주는 예시라고 볼 수도 있겠습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// ChildClass 객체의 존재를 확인하기 위한 RoundRect</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">120</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">ROLL_OUT</span>, rollOutHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> rollOutHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;부모 객체가 자식 객체에게 dispatchEvent() 한 MouseEvent.ROLL_OUT 을 캐치함 !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>부모 객체(왼쪽에 그려진 RoundRect 그림)를 클릭하면 자식 객체에게 MouseEvent.ROLL_OUT 이벤트를 발생시킬수가 있습니다. 또한 자식객체에는 addEventListener( MouseEvent.ROLL_OUT ) 가 걸려 있으므로 자식 객체를 표시한 오른쪽 RoundRect 그림에 마우스를 올렸다가 밖으로 빼도 동일한 이벤트가 발생하게 됩니다.</p>
<h3>F. 이벤트 발생위치를 바꿈</h3>
<p>E 케이스의 코드는 부모객체가 자식객체에게<sup>[<a href="http://ufx.kr/blog/404#footnote_2_404" id="identifier_2_404" class="footnote-link footnote-identifier-link" title="즉, 자식객체의 입장에서 보면 this.dispatchEvent() 된 것입니다.">03</a>]</sup> dispatchEvent() 메서드를 사용한 것이지만, 반대로 부모객체 내부에서 dispatchEvent() 를 하고 자식객체에서 이것을 addEventListener() 할 수도 있습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">MouseEvent</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ParentClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _roundRect<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span>;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _childInstance<span style="color: #000000; font-weight: bold;">:</span>ChildClass = <span style="color: #0033ff; font-weight: bold;">new</span> ChildClass;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ParentClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 클릭을 위한 RoundRect</span>
			_roundRect.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x996633 <span style="color: #000000;">&#41;</span>;
			_roundRect.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			_roundRect.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
			_roundRect.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">MouseEvent</span>.<span style="color: #004993;">CLICK</span>, clickHandler <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> _roundRect <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> _childInstance <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> clickHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 이번에는 부모 객체인 this 에 dispatchEvent() 를 함</span>
			<span style="color: #009900;">// _childInstance 객체에서 addEventListener() 하고 있건 말건 무조건 이벤트가 발생</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">dispatchEvent</span><span style="color: #000000;">&#40;</span> <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Event</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">SELECT</span> <span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>아래는 자식 객체를 만드는 클래스 입니다. 자세한 내용은 주석을 참고하세요.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.events</span>.<span style="color: #004993;">Event</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> ChildClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> ChildClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// ChildClass 객체의 존재를 확인하기 위한 RoundRect</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">beginFill</span><span style="color: #000000;">&#40;</span> 0x336699 <span style="color: #000000;">&#41;</span>;
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">graphics</span>.<span style="color: #004993;">drawRoundRect</span><span style="color: #000000;">&#40;</span> <span style="color: #000000; font-weight:bold;">120</span>, <span style="color: #000000; font-weight:bold;">10</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">60</span> <span style="color: #000000;">&#41;</span>;
&nbsp;
			<span style="color: #009900;">// 이 객체가 addChild() 되면 핸들러 실행</span>
			<span style="color: #009900;">// 즉, 어떤 객체의 자식 객체가 된 상황</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">ADDED</span>, addedHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> addedHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Event</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #009900;">// 어떤 부모 객체인지는 모르겠지만 부모 객체에 addEventListener() 를 걸어놓음</span>
			<span style="color: #009900;">// addEventListener() 는 ParentClass 형(type)이 아니더라도 사용할 수 있으므로 캐스팅이 필요 없음</span>
			<span style="color: #0033ff; font-weight: bold;">this</span>.<span style="color: #004993;">parent</span>.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span> <span style="color: #004993;">Event</span>.<span style="color: #004993;">SELECT</span>, selectHandler <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> selectHandler<span style="color: #000000;">&#40;</span> $e<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Event</span> <span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;부모 객체의 이벤트를 자식 객체에서 캐치함 !!&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>또는 반대로, 자식 객체에서 this.addEventListener() 하지 않고, 부모객체에서 이벤트가 일어나도록this.parent.dispatchEvent() 한 후, 부모객체가 this.addEventListener() 까지 하게 할 수도 있습니다. 이벤트가 발생(dispatchEvent)하는 위치만 다를뿐 부모, 자식 객체간은 서로를 자유롭게 참조할 수 있으므로 addEventListener() 메서드는 어디나 걸어 놓을 수 있는 것이죠.</p>
<p>이렇게 부모, 자식 객체간의 여러가지 상황에서 서로를 참조하는 방법에 대해 알아보았습니다. 어떤 방법이 절대적으로 옳지 않으므로 상황에 따라 적절하게 사용하면 됩니다. 또한, 어떤 방법이 절대적으로 옳은건 아니지만, 모든 방법을 제대로 이해하고 있어야 합니다. 그 만큼 객체 지향 프로그래밍에서 가장 기초적이고 중요한 내용입니다.</p>
<p>이해가 잘 안되는 케이스가 있다면, 빈 fla 파일에 ParentClass 를 도큐먼트 클래스로 설정하고 컴파일을 해 보세요.</p>
<p style="text-align: center;">* * *</p>
<p>만약 이벤트와 함께 데이터를 보내야 할 필요가 있을 경우에는 커스텀 이벤트를 사용하면 됩니다. 커스텀 이벤트는 이 포스트의 범위를 벗어나는 내용이므로 &#8220;<a href="http://ufx.kr/blog/228">이벤트에 뭔가 같이 보내보자 &#8211; 커스텀 이벤트 만들고 사용해보기</a>&#8221; 를 읽어보시기 바랍니다.</p>
<p>또한, 객체간 더욱 약한 결합을 구현하기 위한 별도의 방법으로는 옵저버 디자인 패턴을 이용하는 방법이 있습니다. &#8220;<a href="http://ufx.kr/blog/233">Observer Pattern 옵저버 패턴 – 이벤트 디스패처를 이용해 구현</a>&#8221; 을 참고하세요.</p>
<p>이 포스트는 부모, 자식 객체간 참조 방법을 다룬 글이었습니다. 객체가 아닌 상위 클래스와 하위 클래스의 참조 방법에 대한 글 &#8220;<a href="http://ufx.kr/blog/407">AS3.0 클래스의 상속(extends)구조에서 상위, 하위 클래스의 메서드 호출방법</a>&#8221; 도 초보 개발자 여러분들에게 많은 도움이 될 것입니다.</p>
<ol class="footnotes"><li id="footnote_0_404" class="footnote">Object &#8211; EventDispatcher &#8211; DisplayObject &#8211; InteractiveObject &#8211; DisplayObjectContainer &#8211; Sprite</li><li id="footnote_1_404" class="footnote">Object, EventDispatcher, DisplayObject, InteractiveObject,  DisplayObjectContainer 의 메서드, 속성만 사용할 수 있고, Sprite 이하의 메서드, 속성은 사용할 수 없습니다.</li><li id="footnote_2_404" class="footnote">즉, 자식객체의 입장에서 보면 this.dispatchEvent() 된 것입니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/404/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>다른 액션스크립트 개발자들은 어떻게 코딩을 하는지 궁금해?</title>
		<link>http://ufx.kr/blog/396</link>
		<comments>http://ufx.kr/blog/396#comments</comments>
		<pubDate>Mon, 01 Mar 2010 16:58:35 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[codesearch]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[IE]]></category>
		<category><![CDATA[개발자]]></category>
		<category><![CDATA[검색도구]]></category>
		<category><![CDATA[구글]]></category>
		<category><![CDATA[오픈소스]]></category>
		<category><![CDATA[코딩]]></category>
		<category><![CDATA[클래스]]></category>
		<category><![CDATA[파이어폭스]]></category>
		<category><![CDATA[프로그래밍]]></category>
		<category><![CDATA[프로젝트]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=396</guid>
		<description><![CDATA[프로그래밍적 지식 기반이 없는 비 전공 출신의 액션스크립트 개발자에게는 다른 개발자들이 어떻게 코딩을 하는가가 지대한 관심사 중의 하나입니다. 특히나 액션스크립트는 세상에 나온지 아무리 길게 봐줘도 10년 밖에 안되는데다가, 제대로 된 프로그래밍적 형식과 구조를 갖추게 된 것은 AS3.0부터라고 봐야 하므로 이제 고작 4년 남짓 된 언어라고 할 수 밖에 없습니다. 정규 교육 시스템이 부족하여 사수-부사수 (도제) [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-397" title="code_ship" src="http://ufx.kr/blog/wp-content/uploads/2010/03/code_ship.jpg" alt="" width="320" height="350" />프로그래밍적 지식 기반이 없는 비 전공 출신의 액션스크립트 개발자에게는 다른 개발자들이 어떻게 코딩을 하는가가 지대한 관심사 중의 하나입니다. 특히나 액션스크립트는 세상에 나온지 아무리 길게 봐줘도 10년 밖에 안되는데다가, 제대로 된 프로그래밍적 형식과 구조를 갖추게 된 것은 AS3.0부터라고 봐야 하므로 이제 고작 4년 남짓 된 언어라고 할 수 밖에 없습니다. 정규 교육 시스템이 부족하여 사수-부사수 (도제) 시스템에 의한 학습에 의존해야 하는 편이죠.</p>
<p>도제 시스템에 의한 학습의 기회라도 있었다면 그나마 운이 좋은 쪽이랄까요. 액션스크립트를 다루는 사람들의 출신성분중 대다수를 차지하는 디자이너 계통은 거의 대부분 독학으로 액션스크립트를 배우게 됩니다. 이래서야 제대로된 플래시 애플리케이션이 나올리가 없겠죠. 객체지향이라는 개념조차 피상적으로만 이해할 뿐, AS2.0이나 다를바 없이 메인타임라인에 코드 늘어놓기만 한참 하기 마련입니다. 도큐먼트 클래스를 사용할 수 있게 되고 자신이 직접 코딩한 클래스를 new 키워드로 객체 생성하여 사용할 수 있게 되기까지는 참으로 오랜 시간이 필요합니다.</p>
<p>특히, 다른 개발자와 협업을 해야 하거나, 유지보수를 위해 내가 개발한 코드를 다른 사람에게 넘겨 줘야 하는 경우라면 독학에 의한 프로그램적 구멍(?)이 더욱 눈에 띄게 됩니다.<br />
이런 현상들은 여러가지 원인이 있겠지만, 결국 다른사람은 어떻게 코딩하는지 잘 모르기 때문에(나홀로 코딩) 생기는 것이라 할수 있습니다. 그렇다고 다짜고짜 플래시 동네의 유명한 누군가에게 가서 &#8220;공부 좀 하게 코드를 내놔라&#8221; 라고 할 수도 없는 노릇이고 말이죠.</p>
<p><span id="more-396"></span><br />
이럴 때 좋은 참고자료가 되는 것이 <a href="http://www.google.com/codesearch?hl=ko" target="_blank">구글코드검색</a> 입니다.<br />
구글코드검색으로 구글 코드의 <a href="http://code.google.com/intl/ko/projecthosting/" target="_blank">프로젝트 호스팅</a>을 통해 전세계 개발자들이 협업 또는 오픈소스 프로젝트를 진행하면서 공개한 코드를 검색해 볼 수 있습니다.</p>
<p><a href="http://www.google.com/codesearch?hl=ko"><img class="alignnone size-full wp-image-398" title="google_codesearch_1" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_1.png" alt="" width="598" height="382" /></a></p>
<p>위의 이미지와 같이 검색창에 키워드와 한칸 띄고 lang:actionscript 를 추가해 넣으면 해당 키워드에 대한 액션스크립트 코드를 검색할 수 있습니다. 마우스 포인터가 가리키는 &#8220;<a href="http://www.google.com/codesearch/advanced_code_search?hl=ko" target="_blank">고급코드검색</a>&#8220;으로 들어가면, 위에서 한 것과 같은 프로그램 언어 설정이라던지, 라이센스, 패키지 등의 세부적인 설정과 함께 검색을 할 수 있습니다. 위의 스크린샷에 나온대로 검색하면 스트래티지 패턴(strategy pattern:전략패턴)에 관한 액션스크립트 클래스들이 검색되겠죠.</p>
<p><a href="http://www.google.com/codesearch/advanced_code_search?hl=ko"><img class="alignnone size-full wp-image-399" title="google_codesearch_2" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_2.png" alt="" width="601" height="428" /></a></p>
<p>액션스크립트가 가장 위에 있죠? 알파벳 순서로 정렬되어 있기 때문인데, 스크롤을 하지 않아도 되서 편리합니다.</p>
<p>검색된 코드는 실무 프로젝트인 경우가 압도적으로 많으므로, 전체 프로젝트를 전반적으로 이해하지 않으면, 초보 개발자의 눈에는 이 클래스가 뭐하는 클래스인지 단번에 이해하기 어려운 점이 있기도 합니다만, 분명 다른 개발자의 코드를 참고할 수 있다는 것만으로 위안이 될 겁니다. ^^</p>
<p>또한 구글코드에서 검색되는 클래스들은 대부분 어느 수준 이상의 완성도가 보장되어 있습니다. 오픈소스로 공개되어 있는 코드들이기 때문에 공개하기 전 다른 개발자들이 제대로 사용할 수 있도록 자체 검증을 거치게 되기 때문입니다. 물론, 미완성이나 오작동하는 클래스도 간혹 존재합니다만, 이런 것을 가려서 참고를 하는 것은 역시나 사용자의 몫이 되겠죠.</p>
<p style="text-align: center;">* * *</p>
<p>보너스로 웹 브라우저의 검색도구에 구글코드검색을 추가하는 방법을 알아보겠습니다.</p>
<h4><span style="color: #33cccc;">FireFox 의 검색 도구에 codesearch 추가하기</span></h4>
<p>FireFox 에서는 간단히 애드온을 설치하기만 하면 됩니다.<br />
<a href="https://addons.mozilla.org/ko/firefox/addon/46201" target="_blank">https://addons.mozilla.org/ko/firefox/addon/46201</a></p>
<h4><a href="https://addons.mozilla.org/ko/firefox/addon/46201"><img class="alignnone size-full wp-image-403" title="google_codesearch_4_ff" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_4_ff.png" alt="" width="599" height="457" /></a></h4>
<h4></h4>
<h4><span style="color: #33cccc;">Internet Explorer 의 검색 공급자에 codesearch 추가하기</span></h4>
<p style="text-align: center;"><img class="size-full wp-image-400 aligncenter" title="google_codesearch_3_ie_1" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_3_ie_1.png" alt="" width="317" height="336" /></p>
<p>IE의 경우 검색 공급자 풀다운 메뉴를 눌러 &#8220;<a href="http://www.ieaddons.com/kr/searchproviders" target="_blank">추가 검색 공급자 찾기&#8230;</a>&#8221; 를  선택합니다.</p>
<p><a href="http://www.ieaddons.com/kr/searchproviders"><img class="alignnone size-full wp-image-401" title="google_codesearch_3_ie_2" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_3_ie_2.png" alt="" width="600" height="179" /></a></p>
<p>이 페이지의 가장 아랫 부분에 있는 &#8220;<a href="http://www.ieaddons.com/CreateSearch.aspx" target="_blank">나만의 검색 공급자 만들기</a>&#8220;를  클릭합니다.</p>
<p><a href="http://www.ieaddons.com/kr/createsearch.aspx"><img class="alignnone size-full wp-image-402" title="google_codesearch_3_ie_3" src="http://ufx.kr/blog/wp-content/uploads/2010/03/google_codesearch_3_ie_3.png" alt="" width="600" height="776" /></a></p>
<p>그런 후 나온 페이지에서 URL 입력에 액션스크립트 검색 설정을 포함한 검색 결과인  http://www.google.com/codesearch?hl=en&amp;lr=&amp;q=TEST+lang%3Aactionscript&amp;sbtn=Search  를 입력하고, Name 에는 표시될 적당한 이름을 입력해 준 후, 검색 공급자 설치 버튼, 추가 버튼 클릭 하면 IE의 오른쪽 위의 검색공급자에 Google CodeSearch 가 추가됩니다.</p>
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/396/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>액션스크립트 3.0 입문자를 위한 F1 도움말(레퍼런스) 보는 방법</title>
		<link>http://ufx.kr/blog/378</link>
		<comments>http://ufx.kr/blog/378#comments</comments>
		<pubDate>Wed, 13 Jan 2010 06:30:09 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[ASdoc]]></category>
		<category><![CDATA[CS4]]></category>
		<category><![CDATA[CS5]]></category>
		<category><![CDATA[F1]]></category>
		<category><![CDATA[개발자]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[도움말]]></category>
		<category><![CDATA[레퍼런스]]></category>
		<category><![CDATA[메서드]]></category>
		<category><![CDATA[상속]]></category>
		<category><![CDATA[속성]]></category>
		<category><![CDATA[이벤트]]></category>
		<category><![CDATA[클래스]]></category>
		<category><![CDATA[패키지]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=378</guid>
		<description><![CDATA[우리가 흔히 F1 또는 레퍼런스라고 부르는 플래시 도움말이 있습니다. 개발자들 사이에서는 이 레퍼런스의 형식을 ASDoc(ActionScript Documentation) 이라고 부르기도 합니다.[01] Java 개발자들을 위한 JavaDoc 도 구경해볼까요? J2EE 의 1.4 버전 레퍼런스 입니다. 구글에서 개발한 스마트폰 운영체제인 안드로이드도 개발자들을 위한 레퍼런스를 제공하고 있는데, 이것의 형태도 크게 다르지 않습니다. 레퍼런스란 필요한 부분을 검색하여 원하는 정보를 찾아보는 대상을 의미 [...]]]></description>
			<content:encoded><![CDATA[<p>우리가 흔히 F1 또는 레퍼런스라고 부르는 <a href="http://help.adobe.com/ko_KR/AS3LCR/Flash_10.0/" target="_blank">플래시 도움말</a>이 있습니다. 개발자들 사이에서는 이 레퍼런스의 형식을 ASDoc(ActionScript Documentation) 이라고 부르기도 합니다.<sup>[<a href="http://ufx.kr/blog/378#footnote_0_378" id="identifier_0_378" class="footnote-link footnote-identifier-link" title="ASDoc은 작은의미로 Flex SDK에 포함된 레퍼런스를 만드는 프로그램의 이름이기도 한데, 이 포스트에서는 그것보다는 큰 의미로 레퍼런스와 동일한 의미로 사용하였습니다.">01</a>]</sup><br />
Java 개발자들을 위한 JavaDoc 도 구경해볼까요? <a href="http://java.sun.com/j2ee/1.4/docs/api/" target="_blank">J2EE 의 1.4 버전 레퍼런스</a> 입니다.<br />
구글에서 개발한 스마트폰 운영체제인 <a href="http://developer.android.com/reference/packages.html" target="_blank">안드로이드도 개발자들을 위한 레퍼런스</a>를 제공하고 있는데, 이것의 형태도 크게 다르지 않습니다.</p>
<p><img class="alignleft" title="reference" src="http://farm3.static.flickr.com/2547/3794323660_09ab487421_m.jpg" alt="" width="240" height="171" />레퍼런스란 필요한 부분을 검색하여 원하는 정보를 찾아보는 대상을 의미 합니다. 레퍼런스는 그 자체로 이미 사전과 같은 역할을 하는 것인데 개발자 출신이 아닌 플래시 액션스크립터 지망생들은 이 레퍼런스를 어려워 하여 멀리하고 오히려 포털 검색으로 지식을 얻으려고 하는 경향이 있습니다.<br />
차라리 검색을 구글에서라도 하면 상위에 리스트업 되는 Adobe 의 레퍼런스를 보게 될 텐데, 그것도 아니고 국내 포털 검색으로 주로 지식검색이나 카페에서 자신과 딱 맞는 케이스의 질문과 답변을 얻으려고 하니 참으로 딱한 상황이 아닐 수 없습니다. 이러한 경향은 지식검색이 만능이라고 생각하는 우리나라에서 좀더 두드러지는 경향이기도 하지만, 외국이라고 예외는 아니어서 <a href="http://ko.wikipedia.org/wiki/RTFM" target="_blank">RTFM 라는 재미있는 관용구</a>도 있습니다.</p>
<p>어쨌건 이러한 형태의 레퍼런스에 친숙해 진다면 다른 언어로 개발하는 것도 꿈속의 일만은 아니게 되는것이죠. 우리에겐 레퍼런스가 있으니까요.</p>
<p><span id="more-378"></span></p>
<p><img class="alignnone size-full wp-image-379" title="reference_01_layout" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_01_layout.gif" alt="reference_01_layout" width="600" height="369" /></p>
<h3>1. 패키지 영역</h3>
<p>패키지는 여러 클래스의 묶음 단위라고 이해하면 어렵지 않습니다. 우리가 가장 많이 사용하는 flash.display 패키지를 클릭하면 아래쪽 클래스 영역의 내용이 flash.display 항목들로만 필터링 되서 보여지고, 본문 영역도 그에 맞게 화면이 변경 됩니다.<br />
레퍼런스에서 패키지 영역은 일종의 대분류 목차와 같은 성격을 가지고 있습니다. 클래스 이름을 알고 있다면 굳이 클릭할 필요가 없는 영역이기도 하죠.</p>
<p>그러나 이 영역에만 있어 별도로 살펴봐야할 항목도 몇 가지 있습니다.<br />
스크롤바를 죽 내려보면 &#8220;패키지&#8221; 부분과 &#8220;언어요소&#8221; 부분, 그리고 &#8220;부록&#8221; 부분이 있는데 이것들 중 아래에 나열한 것들은 한번 쯤 훑어 보고 뭐가 있는지는 파악해 놓는게 좋습니다.</p>
<ul>
<li>최상위 : import 를 사용하지 않아도 바로 사용할 수 있는 클래스들과 전역상수, 전역함수 들이 나열되어 있습니다. 우리가 흔히 사용하는 Array, String, Number 등이 최상위 클래스에 속합니다.</li>
<li>연산자 : 사실상 액션스크립트의 모든 기호는 연산자 입니다. 게다가 new 같은 것들도 연산자의 범주에 들어갑니다.</li>
<li>명령문, 키워드 및 지시문 : 프로그래밍의 형식이나 골격을 구성하는 것들 입니다. package, class, public, var, this 등이 여기에 속합니다.</li>
<li>ActionScript 2.0 마이그레이션 : AS2.0의 클래스, 메서드, 속성이 AS3.0 으로 어떻게 변경 되었는지 리스트업 되어있습니다. (이 문서가 여기 있다는것만 알면 됩니다.)</li>
</ul>
<p>나머지 부분들은 읽어본다면 어떤 형태로건 도움이 될 수 있지만, 딱히 읽지 않아도 지장이 없는 부분이므로 대략 스물스물 넘어가도 되겠습니다.</p>
<h3>2. 클래스 영역</h3>
<p>이 영역은 크게 클래스와 인터페이스 항목으로 나뉘는데, 이 중 이탤릭체로 되어 있는 애들이 인터페이스 입니다. AS3.0을 처음 배워나가는 과정에서는 인터페이스를 몰라도 괜찮기도 하고, 이 포스트의 내용에서 벗어나는 내용이므로 다음 기회를 잡아 설명하도록 하겠습니다.</p>
<p>이 영역을 스크롤 해서 보면 액션스크립트에서 사용하는 모든 클래스들이 나열되어 있습니다. 클래스의 이름을 알고 있다면, 딱히 검색할 필요 없이 클릭으로 본문 영역에 필요한 정보를 펼칠 수가 있습니다.</p>
<h3>3. 본문 영역</h3>
<p>우리가 가장 흔하게 사용하는 객체인 Sprite 를 펼쳐보겠습니다.</p>
<p><img class="alignnone size-full wp-image-380" title="reference_02_sprite_head" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_02_sprite_head.png" alt="reference_02_sprite_head" width="600" height="443" /></p>
<h4>(1) 패키지</h4>
<p>이 클래스가 어디 소속인지 알려줍니다. Sprite 클래스는 물리적으로 flash.display.Sprite 라는 경로에 있다는 것을 의미하죠. 실제로 액션스크립트의 내장 클래스는 플래시 플레이어에 내부에 들어 있으므로 실재로  Sprite.as 파일이 존재하지는 않습니다만,<sup>[<a href="http://ufx.kr/blog/378#footnote_1_378" id="identifier_1_378" class="footnote-link footnote-identifier-link" title="모든 내장 클래스들이 마찬가지 입니다.">02</a>]</sup> 실제로 파일이 존재한다고 생각해도 무방합니다.</p>
<h4>(2) 클래스</h4>
<p>클래스 정의를 표현 합니다. Sprite 클래스의 경우 어디서나 자유롭게 불러 사용할 수 있는 public 접근 제한을 가지고 있으며, class 라는 것을 의미합니다.</p>
<h4>(3) 상속</h4>
<p>이 클래스의 상속 체인을 모두 표시해 줍니다. Sprite 클래스가 정말 저렇게 5단계에 걸친 많은 클래스를 상속하고 있냐고요? 네 정말 그렇습니다. Sprite 는 이벤트를 발생시키기도 해야하고(EventDispatcher), 시각적인 표현도 해야하고(DisplayObject), 마우스 인터랙션도 받아야 하는데다가(InteractiveObject), Sprite 안에 있는 여러 가지 다른 요소들의 위 아래 순서도 정의해야 하기 때문에(DisplayObjectContainer) 해야 할 일이 꽤나 많은편이죠.</p>
<h4>(4) 하위클래스</h4>
<p>Sprite 클래스를 상속한 클래스의 목록 입니다.</p>
<h4>(5) 언어 버전</h4>
<p>이 클래스를 사용할 수 있는 액션스크립트의 버전입니다.  Sprite 의 경우에는 ActionScript 3.0 부터 사용할 수 있다는 의미입니다.</p>
<p>여기서 잠깐 여러분의 이해를 돕고자 재미있는 이야기를 하나 꺼내보겠습니다.<br />
현재 이 레퍼런스를 사용할 수 있는 ActionScript 버전 중에는 3.0이 가장 낮은 버전입니다. &#8220;당연하잖아!&#8221; 라고 생각하시는 분들에게 아래와 같이 질문을 드려볼까요?</p>
<p><span style="color: #ff6600;">&#8220;AS2.0 의 MovieClip 과 AS3.0 의 MovieClip 은 같은 클래스인가요, 다른 클래스 인가요?&#8221;</span></p>
<p>우리는 AS2.0과 3.0 모두에서 MovieClip 을 사용할 수 있고, 사용 방법 또한 같으며, 성질도 다르지 않습니다. 그러나 아래의 스크린샷을 볼까요?</p>
<p><img class="alignnone size-full wp-image-381" title="reference_03_as3movieclip" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_03_as3movieclip.png" alt="reference_03_as3movieclip" width="600" height="222" /></p>
<p>그런데 뭔가 이상하죠? MovieClip 은 분명 AS2.0 에서도 사용할 수 있는데, 어째서 언어 버전이 ActionScript 3.0 이라고 써 있으며 런타임 버전 AIR 1.0, Flash Player 9 일까요?</p>
<p><img class="alignnone size-full wp-image-382" title="reference_04_as2movieclip" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_04_as2movieclip.png" alt="reference_04_as2movieclip" width="601" height="257" /></p>
<p>그 해답은 AS2.0 레퍼런스를 보면 알 수 있습니다. 이걸 보면 AS2.0의 MovieClip 과 AS3.0의 MovieClip 은 <span style="color: #ff6600;">클래스 이름은 같지만</span> 엄밀히 말하면 <span style="color: #ff6600;">별개의 클래스</span>라는 것을 알 수 있습니다.</p>
<p>우선 상속 체인이 완전히 다릅니다. AS2.0은 Object 에서 단 한번 상속했을 뿐이지만, AS3.0의 MovieClip 은 위에서 살펴본 Sprite 를 상속 했으니까 무려 6단계의 상속 체인을 가지고 있습니다.</p>
<p>또한 속성도 다르죠. AS2.0이 AS3.0으로 바꼈어도 MovieClip 이라는 클래스 명은 동일하기 때문에 개발의 편의를 위하여 대부분의 속성명을 동일하게 유지했지만, 속성명 앞에 있던 _ (언더 바 또는 언더 스코어) 들이 사라졌습니다. 다르게 말한다면 속성이 죄다 바뀐거라고 할 수 있습니다.</p>
<h4>(6) 런타임 버전</h4>
<p>Flash Player 또는 AIR 런타임<sup>[<a href="http://ufx.kr/blog/378#footnote_2_378" id="identifier_2_378" class="footnote-link footnote-identifier-link" title="AIR의 R은 이미 Runtime 의 이니셜 입니다만, 여기서는 런타임이라는 것을 강조하기 위하여 상가&amp;#8221;집&amp;#8221; 식의 중복을 사용했습니다.">03</a>]</sup> 의 최소 요구 버전을 나타냅니다.<br />
초보분들은 Flash Player 의 버전과 ActionScript 의 버전, 그리고 Flash IDE의 CS 버전은 서로 다른 것을 이야기하는 것이므로 혼동하지 마시기 바랍니다.</p>
<p><img class="alignnone size-full wp-image-383" title="reference_05_publishing_menu" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_05_publishing_menu.png" alt="reference_05_publishing_menu" width="476" height="650" /></p>
<h4>(7) 그리고 개괄적 설명</h4>
<p>이 부분은 이 클래스의 성격과 특성을 나타내므로 새로운 클래스를 만나게 되면 한번씩은 정독 해주는것을 권장합니다.</p>
<h4>(8) 참고 사항</h4>
<p>이 부분은 레퍼런스에 존재하는 관련 사항의 링크나 <a href="http://help.adobe.com/ko_KR/ActionScript/3.0_ProgrammingAS3" target="_blank">Adobe Flash용 Adobe ActionScript 3.0 프로그래밍</a>쪽의 관련 페이지 링크를 제공하기도 합니다. 문제 해결에 결정적인 도움을 주기도 하는 부분이니 디버깅 할 경우라면 주의깊게 살펴보세요.</p>
<p style="text-align: center;">* * * * *</p>
<p style="text-align: center;">여기부터는 본문의 속성, 메서드, 이벤트 목록을 표시하는 부분 입니다.</p>
<h4 style="text-align: center;">- Public 속성 -</h4>
<p><img class="alignnone size-full wp-image-384" title="reference_06_properties" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_06_properties.png" alt="reference_06_properties" width="601" height="327" /></p>
<p>&#8220;상속되는 Public 속성 표시&#8221; 는 클릭하면 &#8220;상속되는 Public 속성 숨기기&#8221;로 링크가 변경됩니다. 이 기능은 클래스가 상속을 하게 되면 부모의 속성, 메서드, 이벤트도 모두 가지게 되기 때문에 상속체인상의 하위 클래스로 갈수록 속성, 메서드, 이벤트의 숫자가 상당히 많아집니다. Sprite 만 봐도 상당히 많은 숫자를 볼 수 있죠.</p>
<p>위 그림에서 우리가 흔하게 사용하는 alpha 속성을 잠시 살펴볼까요? alpha 는 소수점 표시를 해야하기 때문에 Number 의 데이터 형을 가지고 있다는 것을 표시하고 있고, 간단한 설명도 볼 수 있습니다.<br />
오른쪽을 보면 &#8220;다음에 의해 정의됨&#8221; 항목에 DisplayObject 라고 되어 있군요. 즉, alpha 라는 속성은 DisplayObject 에서 정의되어 있으므로 상속 체인상에서 DisplayObject 를 포함한 InteractiveObject, DisplayObjectContainer, Sprite 의 자식 클래스에서 사용 가능하고,  상위 클래스인 EventDispatcher 나 Object 에서는 사용할 수 없는 속성이 되겠습니다.</p>
<p><strong>여기서 잠깐 !</strong></p>
<p>정말 쌩초보스럽지만 정말 중요한 질문하나가 있습니다.<br />
속성은 어떻게 사용하나요?<br />
코드로 보면 아래와 같습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">// 객체 생성 및 초기화</span>
<span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Sprite</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sprite</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">// 객체 속성에 값을 대입함</span>
<span style="color: #009900;">// buttonMode 속성은 Boolean 데이터 형이므로 true 아니면 false 둘 중 하나를 대입해야 함</span>
<span style="color: #009900;">// 객체.속성 = 속성값</span>
instance.<span style="color: #004993;">buttonMode</span> = <span style="color: #0033ff; font-weight: bold;">true</span>;
&nbsp;
<span style="color: #009900;">// 객체 속성을 참조함</span>
<span style="color: #009900;">// 출력 : true</span>
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> instance.<span style="color: #004993;">buttonMode</span> <span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>속성은 클래스 내부에서 getter/setter 로 구현합니다. 읽기전용, 쓰기전용, 읽기쓰기 모두가능의 3가지가 있지만 쓰기전용이라는 것은 실제 사용할 일이 별로 없으므로, 일반적으로 getter 메서드만 있는 읽기전용, getter/setter 둘다 있는 읽기쓰기 모두가능한 두 가지 속성으로 나뉜다고 볼 수 있습니다.<br />
위에서 코드로 예를 든 것과 같이 buttonMode 속성의 경우에는 읽기/쓰기가 모두 가능한 속성이므로 속성에 값을 대입할 수도 있고 값을 참조할 수도 있지만, numChildren 속성 같은 경우는 읽기전용 이므로 대입연산자 = 를 통해 값을 입력할 수 없는 차이가 있습니다.</p>
<p><img class="alignnone size-full wp-image-385" title="reference_07_properties_numchildren" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_07_properties_numchildren.png" alt="reference_07_properties_numchildren" width="600" height="47" /></p>
<p>getter/setter 는 어려운 내용은 아니지만 개념에 대한 이해가 필요하므로 이에대한 설명을 나중에 별도의 포스팅을 하겠습니다.</p>
<h4 style="text-align: center;">- Public 메서드 -</h4>
<p><img class="alignnone size-full wp-image-386" title="reference_08_method" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_08_method.png" alt="reference_08_method" width="601" height="219" /></p>
<p>메서드 역시 부모로부터 상속한 모든 메서드를 사용할 수 있습니다. Sprite 클래스에서 정의한 메서드는 Sprite(), startDrag(), stopDrag() 이 세 가지 뿐이군요.<sup>[<a href="http://ufx.kr/blog/378#footnote_3_378" id="identifier_3_378" class="footnote-link footnote-identifier-link" title="Flash Player 10.1 부터는 모바일 디바이스를 위한 터치관련 메서드들이 조금 더 추가됩니다.">04</a>]</sup> 나머지는 모두 부모 클래스에서 정의한 메서드들이라는 의미 입니다.<br />
위 그림중 우리가 흔하게 사용하는 addChild() 메서드를 살펴보도록 하죠. 함수연산자 () 안에 DisplayObject 타입의 객체가 들어와야 한다는 것을 나타내고 있습니다. child 라는 이름 자체는 의미가 없습니다. 다만 메서드명이 addChild() 이므로 add 하는 대상이 무엇인지 힌트를 주고 있는 것이죠.<br />
그리고 addChild() 메서드가 반환하는 값 역시 DisplayObject 라고 되어있죠? addChild() 의 파마미터에 넣은 child 가 메서드 실행의 결과로 반환됩니다.</p>
<h4 style="text-align: center;">- 이벤트 -</h4>
<p>이벤트는 addEventListener() 나 dispatchEvent() 메서드를 통해 사용하게 됩니다. dispatchEvent() 는 어떻게 사용하는 건데? 라는 질문을 하고 싶은 분이라고 하더라도 나중에 필요할 때 알게 됩니다. addEventListener() 만 사용할 줄 알아도 당장 AS3.0에 입문하는데 지장 없으니 걱정하지 마세요.</p>
<p><img class="alignnone size-full wp-image-387" title="reference_09_events" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_09_events.png" alt="reference_09_events" width="600" height="207" /></p>
<p>이벤트 목록의 오른쪽에 있는 &#8220;다음에 의해 정의됨&#8221;을 보면 Sprite 클래스에서는 정의한 이벤트가 없고 모두 부모 클래스에서 상속한 이벤트 뿐이군요. 사용자의 인터랙션, 즉 마우스나 키보드 입력에 의한 이벤트는 InteractiveObject 에서 상속했고, 인터랙션과 관계 없는 이벤트는 DisplayObject 에서 상속했습니다. 요약설명 부분에 [브로드캐스트 이벤트] 라고 표시되어 있는 것들 중에 몇몇 이벤트는 EventDispatcher 까지 거슬러 올라가기도 합니다.<br />
브로드캐스트 이벤트가 뭔지 궁금한 분은 <a href="http://help.adobe.com/ko_KR/AS3LCR/Flash_10.0/flash/display/DisplayObject.html" target="_blank">여기</a>를 클릭해서 &#8220;DisplayObject 클래스에는 몇 가지 브로드캐스트 이벤트가&#8230;&#8221; 부분을 읽어보세요. 아직까지는 딱히 몰라도 관계 없습니다.</p>
<p style="text-align: center;">* * * * *</p>
<p style="text-align: center;">여기부터는 목록 더 아랫 부분의 상세 설명 본문 부분 입니다.</p>
<h4 style="text-align: center;">- 속성 정보, 생성자 정보, 메서드 정보 -</h4>
<p><img class="alignnone size-full wp-image-388" title="reference_10_properties_view" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_10_properties_view.png" alt="reference_10_properties_view" width="600" height="225" /></p>
<p>레퍼런스의 더 아랫 부분은 위의 이미지와 같은 현재 선택한 클래스의 속성, 메서드, 이벤트에 대한 좀더 자세한 설명이 있습니다. 각 속성이나 메서드의 상세 설명은 사실 알고 있으면 좋지만, 레퍼런스의 모든 부분을 읽는다는건 입문자에겐 불가능할 뿐더러, 읽는다 하더라도 전체적인 그림이 머리속에 그려지지 않은 상태에서는 사실 무슨 의미인지 이해가 되지 않는 경우가 많습니다. 그러므로 아래의 두 가지 방법 중 하나를 선택하는 것이 현실적인 방법 입니다.</p>
<ol>
<li>실제 코딩을 하면서 처음보는 속성이나 메서드가 나오면 레퍼런스에서 찾아서 한번 읽어 보는, 약간 더디지만 확실한 학습 방법.</li>
<li>일단 코딩하면서 문제가 생기게 되면 문제가 생긴 부분의 레퍼런스를 읽어보는, 뭔가 빼먹을 가능성이 있긴 하지만 좀더 빠른 방법.</li>
</ol>
<p>둘 중 자신에게 맞다고 생각하는 방법으로 그때그때 맞게 읽어 나가면 되겠습니다.<br />
중요한 것은 무작정 레퍼런스나 책을 정독 또는 독파한다고 실력이 느는 것이 아니라, 실제 코딩을 해 나가면서 여러가지 문제에 봉착해 보고 해결 방법을 습득해 나가야 한다는 것입니다. <span style="color: #ff6600;">코딩 한줄 하지 않고 실력이 저절로 늘수는 없거든요.</span></p>
<p>본문 영역 중간중간에 해당 속성과 메서드에 해당하는 예제 코드가 있고 가장 아래쪽에 현재 선택된 클래스를 아울러 설명해 주는 예제 코드도 있으니 나중에 필요할 때 이용하면 되겠습니다.<br />
커뮤니티 질문게시판에 올라오는 90%는 이미 레퍼런스에 있는 내용입니다. 버젓이 질문내용과 동일한 코드 예제가 있는 경우도 허다하죠. 다만 어디 있는지 못찾는 것이거나, 찾기 귀찮거나 둘 중 하나입니다.</p>
<p>자, 이렇게 레퍼런스의 구석구석을 설명을 통해 알아 봤습니다. 이제는 레퍼런스의 특정 부분의 의미를 몰라서 레퍼런스를 기피하는 현상은 좀 줄어드리라 기대해 봅니다.</p>
<p style="text-align: center;">* * * * *</p>
<p>글을 쓰는 현재 시점(2010년 1월)은 Flash CS5 가 나오기 직전의 시점이고 CS5 가 베타 버전으로 존재합니다. Flash Player 는 10.1 이 되는군요. 언어 버전은 AS3.0 으로 현재와 변화가 없으므로 골격이나 구조의 변화는 없고 마이너한 요소들이 추가되었습니다.</p>
<p>위에서도 잠깐 설명했지만 액션스크립트의 내장 클래스들은 Flash Player 에 존재합니다. CS4, CS5 와 같은 Flash IDE 버전에 따라 액션스크립트 API가 버전이 올라간다고 생각하기 쉽지만 그렇지 않습니다. Flash IDE는 저작 환경일 뿐이고 액션스크립트 버전과는 직접적인 관계가 없습니다.<sup>[<a href="http://ufx.kr/blog/378#footnote_4_378" id="identifier_4_378" class="footnote-link footnote-identifier-link" title="그러나 한편으로는 Flash IDE버전에 올라가면 Flash Player 의 버전도 같이 올라가는 경우가 대부분이므로 완전히 별개라고 보기에도 어려움이 있긴 합니다.">05</a>]</sup></p>
<p>마지막으로 <a href="http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/frames.html" target="_blank">Flash CS5와 함께 공개될 새로운 레퍼런스</a>의 모습을 구경해 볼까요?<br />
CS4 버전의 현재 레퍼런스와 크게 달라지는 부분은 없습니다. Beta 라고 군데군데 명시되어 있고, Flex Builder 3 에서 Flash Builder 4 로 명칭이 변경된 만큼 Flex 에서 사용하던 mx 패키지가 들어왔습니다. (예전엔 서로 별개의 레퍼런스처럼 취급되었죠)</p>
<div id="attachment_389" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-389 " title="reference_11_filtering_runtimes" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_11_filtering_runtimes.png" alt="reference_11_filtering_runtimes" width="590" height="437" /><p class="wp-caption-text">베타 레퍼런스에 도입된 필터링 시스템 중 Runtimes 필터링</p></div>
<div id="attachment_390" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-390" title="reference_12_filtering_products" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_12_filtering_products.png" alt="reference_12_filtering_products" width="590" height="437" /><p class="wp-caption-text">Products 의 필터링</p></div>
<p>이전에는 없던 필터링 기능이 눈에 띄는데, Runtimes 으로 Flash Player와 AIR를 구분하여 버전별로 필터링 할 수 있게 했고, Products 에는 Flex SDK 버전과 Flash IDE 버전 그리고 Blaze 서버와 LiveCycle, ColdFusion 까지, 액션스크립트와 관련을 가지는 다른 프로그램들의 레퍼런스들을 총 망라 하고 있습니다.<br />
그 결과 왼쪽 패키지 목록과 클래스 목록에서 다루는 패키지와 클래스의 갯수가 꽤 많이 늘어 난 것처럼 보이는데, 적절한 필터링을 해서 사용하면 되겠습니다.</p>
<div id="attachment_391" class="wp-caption alignnone" style="width: 600px"><img class="size-full wp-image-391" title="reference_14_multitouch" src="http://ufx.kr/blog/wp-content/uploads/2010/01/reference_14_multitouch.png" alt="reference_14_multitouch" width="590" height="437" /><p class="wp-caption-text">Flash Player 10.1 에 새로 추가된 Multitouch 클래스</p></div>
<p>이렇게 버전이 올라서 새로운 클래스가 업데이트 되어도 현재의 레퍼런스와는 크게 달라지는 점이 없습니다. 현재의 레퍼런스를 읽는데 어려움이 없다면 앞으로 훨씬 순조로운 개발을 할 수 있게되겠죠.</p>
<ol class="footnotes"><li id="footnote_0_378" class="footnote">ASDoc은 작은의미로 Flex SDK에 포함된 레퍼런스를 만드는 프로그램의 이름이기도 한데, 이 포스트에서는 그것보다는 큰 의미로 레퍼런스와 동일한 의미로 사용하였습니다.</li><li id="footnote_1_378" class="footnote">모든 내장 클래스들이 마찬가지 입니다.</li><li id="footnote_2_378" class="footnote">AIR의 R은 이미 Runtime 의 이니셜 입니다만, 여기서는 런타임이라는 것을 강조하기 위하여 상가&#8221;집&#8221; 식의 중복을 사용했습니다.</li><li id="footnote_3_378" class="footnote">Flash Player 10.1 부터는 모바일 디바이스를 위한 터치관련 메서드들이 조금 더 추가됩니다.</li><li id="footnote_4_378" class="footnote">그러나 한편으로는 Flash IDE버전에 올라가면 Flash Player 의 버전도 같이 올라가는 경우가 대부분이므로 완전히 별개라고 보기에도 어려움이 있긴 합니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/378/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Embed 메타데이터 태그를 이용하여 다른 swf 파일의 그래픽 자원 이용</title>
		<link>http://ufx.kr/blog/361</link>
		<comments>http://ufx.kr/blog/361#comments</comments>
		<pubDate>Sat, 26 Dec 2009 02:45:57 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[attachMovie]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[embed]]></category>
		<category><![CDATA[Flash IDE]]></category>
		<category><![CDATA[instance]]></category>
		<category><![CDATA[Linkage]]></category>
		<category><![CDATA[MovieClip]]></category>
		<category><![CDATA[Sprite]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[그래픽 자원]]></category>
		<category><![CDATA[라이브러리]]></category>
		<category><![CDATA[링키지]]></category>
		<category><![CDATA[식별자]]></category>
		<category><![CDATA[클래스]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=361</guid>
		<description><![CDATA[이번에는 as 파일의 Embed 태그를 이용하여 클래스에서 사용하는 그래픽 자원을 컴파일 타임에 다른 swf 파일에서 가져와 사용하는 방법을 소개합니다. 이 방법은 앞서 포스팅 한 라이브러리의 무비클립에 직접 클래스 파일을 연결한 경우와 비교하여 컴파일러의 선택이라는 측면에서 좀더 넓은 선택의 폭을 제공합니다. 라이브러리에 직접 클래스 파일을 연결한 경우는 최종 컴파일을 Flash IDE에서만 할 수 있는 반면, 오늘 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-282" title="blue_swf_icon" src="http://ufx.kr/blog/wp-content/uploads/2009/07/blue_swf_icon.png" alt="blue_swf_icon" width="256" height="256" />이번에는 as 파일의 Embed 태그를 이용하여 클래스에서 사용하는 그래픽 자원을 컴파일 타임에 다른 swf 파일에서 가져와 사용하는 방법을 소개합니다.</p>
<p>이 방법은 <a href="http://ufx.kr/blog/353">앞서 포스팅 한 라이브러리의 무비클립에 직접 클래스 파일을 연결한 경우</a>와 비교하여 컴파일러의 선택이라는 측면에서 좀더 넓은 선택의 폭을 제공합니다. 라이브러리에 직접 클래스 파일을 연결한 경우는 최종 컴파일을 Flash IDE에서만 할 수 있는 반면, 오늘 소개할 Embed 태그를 이용해 그래픽 자원을 클래스에 직접 붙이는 경우에는 Flash IDE에서 컴파일을 할 수도 있고, Flex SDK를 통해 mxmlc 에서 컴파일을 하는 경우에도 사용할 수 도 있습니다. 무슨소리인지 잘 이해가 되지 않으셔도 일단 다음으로 패스! 포스팅의 내용과 살짝 거리가 있는 내용이므로 컴파일러에 대해 다루는 글을 나중에 별도로 포스팅 할 예정입니다.<br />
<span id="more-361"></span></p>
<p style="text-align: center;">***</p>
<p>먼저, fla 파일을 만들어 보겠습니다. 이름을 무엇으로 짓건 관계 없지만 이왕이면 파일이름에 어떤 역할을 하는 파일인지 네이밍을 해 준다면 Flash IDE를 열어서 어떤 파일인지 확인하는 수고를 덜 수 있겠죠. 그러므로 이 파일은 asset 이라는 폴더를 새로 만든 후 그 안에 TestProject_graphic_asset.fla 라고 약간 설명적으로 네이밍을 하고 저장했습니다.</p>
<p>드로잉 도구를 이용하거나 비트맵 이미지등을 import 하여 적당히 디자인을 하고 F8 단축키를 이용해 무비클립으로 만들어 줍니다. 라이브러리에서 방금 만든 MovieClip의 속성창을 열고 class 이름을 부여해 줍니다. 별 그림 이므로 클래스 이름은 MyStar 라고 지어보죠. 이때 Sprite로 만들고 싶으면 <a href="http://ufx.kr/blog/353">라이브러리의 무비클립을 클래스로 만들어 사용하기</a>의 중간에 있는 관련 내용을 살펴보세요.</p>
<p><img class="aligncenter size-full wp-image-362" title="MyStar 무비클립의 속성창" src="http://ufx.kr/blog/wp-content/uploads/2009/12/MyStarClass.png" alt="MyStar 무비클립의 속성창" width="434" height="588" /></p>
<p>무비클립에 클래스 이름을 준 이후에는 무비클립이 스테이지에 놓여있건 아니건 우리나 사용하는데는 관계가 없습니다. 이 fla 파일은 그래픽 자원만을 사용하려는 목적으로 만들어진 것이므로 라이브러리 목록에 클래스 정의되어진 무비클립만 사용할 수 있습니다. 스테이지에 무엇이 놓여있건 최종 결과물과는 관계 없으므로 무비클립들을 배치하여 디자인을 미리 보는 용도로 활용할 수도 있습니다. 전체 예제 파일을 다운로드 하여 TestProject_graphic_asset.swf 을 확인해 보세요.</p>
<p>디자인이 완료되면 테스트 무비(Ctrl + ENTER) 나 퍼블리싱 메뉴(Ctrl + Shift + F12)를 통해 swf 를 생성합니다. 별다른 설정을 하지 않았다면 파일이름은 TestProject_graphic_asset.swf 이 되겠습니다. 그렇다면 asset 폴더 안에는 TestProject_graphic_asset.fla 파일과 TestProject_graphic_asset.swf 두개의 파일이 있을 겁니다.</p>
<p>자 그럼, 이 무비클립을 사용할 클래스를 하나 작성합니다. 클래스의 이름은 역시 MyStar 라고 지었는데요, 위에서 TestProject_graphic_asset.swf 의 라이브러리에 지정한 클래스의 이름과 동일하게 네이밍 했습니다. 이름이 반드시 같아야 할 필요는 없지만, 후일 클래스의 그래픽 자원을 라이브러리에서 찾아야 할 경우, 이름이 같으면 쉽게 찾을 수 있으므로 잇점이 생기는 거죠.</p>
<p>클래스 내용은 아래와 같습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span> items
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #000000;">&#91;</span>Embed<span style="color: #000000;">&#40;</span><span style="color: #004993;">source</span>=<span style="color: #990000;">'../../asset/TestProject_graphic_asset.swf'</span>, symbol=<span style="color: #990000;">'MyStar'</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MyStar extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
&nbsp;
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>src 폴더를 만들고 다시 그 안에 items 폴더를 만들어 MyStar.as 파일을 그 안에 저장했습니다. Embed 태그 의 source 속성에 swf 파일의 경로를 as 파일 기준으로 넣어주고, symbol 속성에 TestProject_graphic_asset.fla 의 라이브러리에 지정했던 클래스 이름이 들어가 있는 것이 보입니다. 이 클래스는 아직까지 그림 외에는 별다른 역할을 하지 않으므로 생성자 함수조차도 필요 없습니다. TestProject_graphic_asset.fla 파일의 라이브러리에는 MyEarth 클래스도 하나 더 만들어 놓았습니다. MyEarth.as 파일은 하단에 있는 전체 파일 다운로드에서 확인하세요.</p>
<p>여기까지 하면 모든 준비가 끝났습니다. 아래 도큐먼트 클래스에서 new 연산자로 MyStar 객체를 생성하고 addChild 메서드를 통해 화면에 표시했습니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
	<span style="color: #0033ff; font-weight: bold;">import</span> items.<span style="color: #000000; font-weight: bold;">*</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> TestProjectMain extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> star<span style="color: #000000; font-weight: bold;">:</span>MyStar;
		<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> earth<span style="color: #000000; font-weight: bold;">:</span>MyEarth;
&nbsp;
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> TestProjectMain<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			star = <span style="color: #0033ff; font-weight: bold;">new</span> MyStar<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> star <span style="color: #000000;">&#41;</span>;
&nbsp;
			earth = <span style="color: #0033ff; font-weight: bold;">new</span> MyEarth<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
			<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> earth <span style="color: #000000;">&#41;</span>;
			earth.<span style="color: #004993;">x</span> = star.<span style="color: #004993;">width</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위의 도큐먼트 클래스를 Flash Builder 나 FlashDevelop 등의 외부 에디터에서 직접 컴파일을 해도 무방하지만, 이번에는 TestProjectMain.fla 파일에 연결하여 컴파일을 해 보겠습니다. 아래 컴파일 결과에서 보는것과 같이 TestProjectMain.fla 파일에는 배경이미지가 있습니다.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="600" height="223" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://ufx.kr/blog/wp-content/uploads/2009/12/TestProjectMain.swf" /><embed type="application/x-shockwave-flash" width="600" height="223" src="http://ufx.kr/blog/wp-content/uploads/2009/12/TestProjectMain.swf"></embed></object></p>
<p>이 방법이 가져다 주는 장점으로는 디자인단과 개발단이 명확하게 구분되어 협업 시스템에서 큰 이득을 가져다 주는 것이라고 할 수 있겠습니다. 디자이너는 그래픽 자원만을 가지고 있는 fla 파일을 수정하면 되고, 수정이 완료되면 컴파일 한번, 해야할 일은 그것으로 끝 입니다.</p>
<p>한편 개발자는 코딩을 하고 최종 컴파일을 하는 권한(또는 의무)을 가지게 됩니다. 디자인과 개발을 분업할 만한 정도 규모의 프로젝트라면 최종 컴파일은 개발자가 하는 것이 유리하다고 할 수 있고, 게다가 누군가 fla 파일을 열고 있으면 다른 사람이 수정하거나 심지어는 copy 조차도 되지 않은 fla 파일의 특성상, 개발자는 TestProject_graphic_asset.fla 파일을 만질 필요가 없고, 디자이너는 TestProjectMain.fla 파일을 만질 필요가 없는 이런 작업영역 분배는 상당히 바람직한 방법이라 할 수 있겠습니다.</p>
<a href="http://ufx.kr/blog/wp-content/plugins/download-monitor/download.php?id=22" title="Downloaded 523 times"><img src="http://ufx.kr/blog/wp-content/uploads/2009/07/zip_icon.gif" />&nbsp; Embed 태그를 이용한 그래픽 자원 사용 예제</a> - fla 는 CS4에서 생성
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/361/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>라이브러리의 무비클립을 클래스로 만들어 사용하기</title>
		<link>http://ufx.kr/blog/353</link>
		<comments>http://ufx.kr/blog/353#comments</comments>
		<pubDate>Mon, 21 Dec 2009 17:21:14 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[attachMovie]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[Flash IDE]]></category>
		<category><![CDATA[instance]]></category>
		<category><![CDATA[Linkage]]></category>
		<category><![CDATA[MovieClip]]></category>
		<category><![CDATA[Sprite]]></category>
		<category><![CDATA[고수들은 가르져주지 않아요]]></category>
		<category><![CDATA[라이브러리]]></category>
		<category><![CDATA[식별자]]></category>
		<category><![CDATA[클래스]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=353</guid>
		<description><![CDATA[&#8220;고수들은 가르쳐주지 않아요&#8221; 시리즈의 첫 포스트는 라이브러리에 있는 무비클립을 클래스로 만들어 사용하는 방법 입니다. AS2.0 방식[01] 으로는 attachMovie() 메서드를 사용하는 경우에 해당하죠. AS3.0 에서는 기존의 linkage[02] 를 사용할 수 없는 대신, class 정의를 하고 new 연산자를 통해 객체를 생성한다는것은 알고 계실 겁니다. 라이브러리에 등록된 무비클립의 속성을 선택하면 아래와 같은 화면을 볼 수 있습니다. AS2.0 같으면 [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;고수들은 가르쳐주지 않아요&#8221; 시리즈의 첫 포스트는 라이브러리에 있는 무비클립을 클래스로 만들어 사용하는 방법 입니다. AS2.0 방식<sup>[<a href="http://ufx.kr/blog/353#footnote_0_353" id="identifier_0_353" class="footnote-link footnote-identifier-link" title="별도의 지칭이 없는 한 이 블로그에서 AS2.0 방식 프로그래밍이라 함은 클래스를 이용하는 방식이 아닌, fla 파일의 타임라인에 코딩하는 방식을 이야기 합니다.">01</a>]</sup> 으로는 attachMovie() 메서드를 사용하는 경우에 해당하죠.</p>
<p>AS3.0 에서는 기존의 linkage<sup>[<a href="http://ufx.kr/blog/353#footnote_1_353" id="identifier_1_353" class="footnote-link footnote-identifier-link" title="한글판 Flash IDE 에는 &amp;#8220;식별자&amp;#8221;라는 명칭으로 되어있습니다만, 영어 단어를 발음 그대로 옮겨쓴 &amp;#8220;링키지&amp;#8221;로 더 많이 알려져 있죠.">02</a>]</sup> 를 사용할 수 없는 대신, class 정의를 하고 new 연산자를 통해 객체를 생성한다는것은 알고 계실 겁니다. 라이브러리에 등록된 무비클립의 속성을 선택하면 아래와 같은 화면을 볼 수 있습니다.</p>
<div id="attachment_354" class="wp-caption aligncenter" style="width: 461px"><img class="size-full wp-image-354" title="making class" src="http://ufx.kr/blog/wp-content/uploads/2009/12/making_class.png" alt="라이브러리에 있는 무비클립의 속성메뉴를 선택한 화면" width="451" height="383" /><p class="wp-caption-text">라이브러리에 있는 무비클립의 속성메뉴를 선택한 화면</p></div>
<p><span id="more-353"></span>AS2.0 같으면 라이브러리 무비클립의 linkage 를 myMc 같은 스타일로 네이밍 했겠죠? AS3.0 은 본격적인 클래스 기반 프로그래밍이므로 MyClass 라고 네이밍 해 보았습니다. 클래스 이름의 첫 알파벳은 대문자로 시작하는것이 통상이므로 그것 역시 반영하였습니다.</p>
<p>그래서 이렇게 설정해 놓았으면, 아래와 같이 사용할 수 있게 되는거죠.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> instance<span style="color: #000000; font-weight: bold;">:</span>MyClass = <span style="color: #0033ff; font-weight: bold;">new</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span> instance <span style="color: #000000;">&#41;</span>;</pre></td></tr></table></div>

<p>그런데 속성을 설정할 때 아래와 같은 대화상자가 나온 분도 있을 것입니다.</p>
<p><img class="aligncenter size-full wp-image-355" title="making_class_alert" src="http://ufx.kr/blog/wp-content/uploads/2009/12/making_class_alert.png" alt="making_class_alert" width="390" height="203" /></p>
<p>이 경고메세지는 &#8220;다시 표시하지 않음&#8221; 에 체크 한 후 닫으면 이후로는 보이지 않습니다. 간혹 영문 Flash IDE<sup>[<a href="http://ufx.kr/blog/353#footnote_2_353" id="identifier_2_353" class="footnote-link footnote-identifier-link" title="우리가 흔히 말하는 Flash CS4, CS5 같은 것들을 Flash IDE (Integrated Development Environment : 통합 개발 환경)라고 말합니다.">03</a>]</sup> 에서 뭔가 자꾸 똑같은 것이 뜨는 것이 귀찮아서 무슨 내용인지도 모른 채 체크한 적이 있는 분은, 이 대화상자의 중요한 의미를 모르고 지나칠뻔 한 경우입니다.</p>
<p>다시 내용으로 돌아갑니다. 저 경고 메세지의 의미는 fla 파일과 같은 디렉토리에는 MyClass.as 라는 파일이 없다는 경고 메세지 입니다. 맞는 말이죠? 이런 파일을 우리는 만든일이 없습니다. 그래서 Flash IDE 는 swf 파일을 내보낼 때<sup>[<a href="http://ufx.kr/blog/353#footnote_3_353" id="identifier_3_353" class="footnote-link footnote-identifier-link" title="컴파일 또는 테스트무비 한다는 의미입니다.">04</a>]</sup>  MyClass.as 를 가상으로 만들어서 임의로 연결 한 후, swf 파일을 생성하게 됩니다.</p>
<p>가상으로 만들어진 그 파일의 내용은 어떤 내용을 가지고 있을까요? 간단합니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">MovieClip</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MyClass extends <span style="color: #004993;">MovieClip</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> MyClass <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>즉, MovieClip 을 상속했고 아직까지는 인스턴스라던가 멤버함수와 같은 다른 내용이 없는 기본형태의 클래스 입니다. 우리가 만들지 않아 Flash IDE가 대신 만들어준 것이죠. 이것은 무엇을 말합니까? 라이브러리에 있는 클래스 화(化) 되어 있는 요소들은 우리가 *.as파일을 만들었건, 만들지 않았건 간에 모두 클래스 정의를 가지고 있다는 것을 말합니다.</p>
<p>&#8220;그럼 Sprite 로는 못만드나요?&#8221;</p>
<p>가능합니다. 클래스 이름란 아래에, 기본 클래스 라는 항목이 있고, 기본값으로 flash.display.MovieClip 이 지정되어 있는것을 가장 위의 스크린샷에서 확인할 수 있었습니다. 이 기본 클래스 항목을 flash.display.Sprite 로 바꿔주면 이 라이브러리 항목은 이제부터 Sprite 를 상속한 녀석이 됩니다. 더 이상 무비클립이 아니죠.</p>
<p style="text-align: center;"><img class="size-full wp-image-357 aligncenter" title="turn_on_sprite" src="http://ufx.kr/blog/wp-content/uploads/2009/12/turn_on_sprite.png" alt="기본 클래스를 Sprite 로 변경해봅니다." width="382" height="152" /></p>
<p>기본 클래스를 MovieClip 에서 Sprite 로 바꾸게 되면, 라이브러리 목록상에 보이는 아이콘의 색상도 아래와 같이 녹색으로 바뀌게 됩니다. 또한 가상으로 만들어지는 MyClass.as 파일도 MovieClip 대신 Sprite 를 상속한걸로 변경됩니다. 타임라인의 2프레임 이상을 사용할일이 없는 그래픽 자원이라면 Sprite 로 바꿔주는 것이 좋겠죠.</p>
<p><img class="aligncenter size-full wp-image-358" title="turned_sprite" src="http://ufx.kr/blog/wp-content/uploads/2009/12/turned_sprite.png" alt="turned_sprite" width="355" height="80" /></p>
<p>만약 이 Sprite 에 MovieClip 이었을적 만들어진 타임라인 애니메이션이 있다면 모두 무시되고 1프레임의 내용만이 유효한 내용으로 고정됩니다.</p>
<p style="text-align: center;">***</p>
<p>위에서는 클래스 정의만 하고 실제 클래스 파일(MyClass.as) 은 만들지 않았는데요, 매우 간단한 플래시 결과물이라면 그렇게 해도 별 지장 없을 것입니다. 클래스 정의를 하긴 하되, 그래픽 자원 이상의 취급을 해주진 않는 거죠.</p>
<p>그러나 점점 난이도와 복잡도가 높은 플래시 애플리케이션을 만들다 보면 클래스 파일이 그림이상의 역할을 해야할 경우가 생깁니다. 따라서 클래스 파일을 실제로 만들고 필요한 변수와 함수를 추가하는 등의 작업을 하게 됩니다만, 이 포스트의 범위를 벗어나는 내용이 되므로 다른 포스트에서 기회가 닿으면 살펴보기로 하고, 실제 클래스 파일을 만들어 연결하는 것은, 가상으로 클래스 파일이 연결되어지는것과 어떤 부분이 다른가를 짚어보도록 하겠습니다.</p>
<p>파일을 실제로 만들기 전에 매우 현실적인 상황 하나를 설정하겠습니다.  만들어야 하는 파일의 갯수가 많아질것을 대비해서 MyClass.as 파일을 fla 파일과 같은 디렉토리가 아닌 &#8220;ui&#8221; 라는 이름의 하위 디렉토리에 넣고 싶어졌다면 어떻게 해야할까요?</p>
<p>다음은 실제로 만들 MyClass.as 파일의 내용입니다.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #9900cc; font-weight: bold;">package</span> ui
<span style="color: #000000;">&#123;</span>
	<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span>.<span style="color: #004993;">Sprite</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #9900cc; font-weight: bold;">class</span> MyClass extends <span style="color: #004993;">Sprite</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span> <span style="color: #990000;">&quot;MyClass 클래스를 이용해 생성된 객체&quot;</span> <span style="color: #000000;">&#41;</span>;
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>위에서 Sprite 로 변경했으므로 그에 맞게 부모클래스를 설정했고, package 키워드 오른쪽에 ui 라고 디렉토리 이름을 붙였습니다.</p>
<p><img class="size-full wp-image-356 alignleft" title="named_package" src="http://ufx.kr/blog/wp-content/uploads/2009/12/named_package.png" alt="named_package" width="345" height="64" />이 파일을 fla 파일 기준 ui 디렉토리에 넣고, Flash IDE의 라이브러리의 MyClass 에 해당하는 Sprite 의 속성을 열고 왼쪽과 같이 디렉토리 경로를 추가해 줍니다. 디렉토리 경로는 곧 패키지 이름과 같게 되는것인데, 이 내용도 차차 알아나가기로 하겠습니다.</p>
<p style="text-align: center;">***</p>
<p>여기까지 확실히 이해를 했다면 Flash IDE 기준의 프로젝트에서 라이브러리의 그래픽 자원을 클래스로 만들어 사용하는 데에는 문제가 없으리라 생각합니다.</p>
<p>이어지는 내용으로는 라이브러리의 그래픽 자원을 클래스 파일에서 이용하는 다른 몇 가지 방법들에 대한 내용이 되겠습니다.</p>
<ol class="footnotes"><li id="footnote_0_353" class="footnote">별도의 지칭이 없는 한 이 블로그에서 AS2.0 방식 프로그래밍이라 함은 클래스를 이용하는 방식이 아닌, fla 파일의 타임라인에 코딩하는 방식을 이야기 합니다.</li><li id="footnote_1_353" class="footnote">한글판 Flash IDE 에는 &#8220;식별자&#8221;라는 명칭으로 되어있습니다만, 영어 단어를 발음 그대로 옮겨쓴 &#8220;링키지&#8221;로 더 많이 알려져 있죠.</li><li id="footnote_2_353" class="footnote">우리가 흔히 말하는 Flash CS4, CS5 같은 것들을 Flash IDE (Integrated Development Environment : 통합 개발 환경)라고 말합니다.</li><li id="footnote_3_353" class="footnote">컴파일 또는 테스트무비 한다는 의미입니다.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/353/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>고수들은 가르쳐주지 않는 액션스크립트 3.0 입문</title>
		<link>http://ufx.kr/blog/347</link>
		<comments>http://ufx.kr/blog/347#comments</comments>
		<pubDate>Mon, 21 Dec 2009 17:20:19 +0000</pubDate>
		<dc:creator>세계의끝</dc:creator>
				<category><![CDATA[고수들은 가르쳐주지 않는 AS3.0 입문]]></category>
		<category><![CDATA[AS2.0]]></category>
		<category><![CDATA[AS3.0]]></category>
		<category><![CDATA[PFG]]></category>
		<category><![CDATA[고수]]></category>
		<category><![CDATA[고수들은 가르쳐주지 않아요]]></category>
		<category><![CDATA[우야꼬]]></category>
		<category><![CDATA[프로]]></category>

		<guid isPermaLink="false">http://ufx.kr/blog/?p=347</guid>
		<description><![CDATA[제목을 위와 같이 잡아 본건 다음과 같은 흥미로운 이야기가 곁들여져 있습니다. 제가 주로 활동하고 있는 플생사모에는 &#8220;고수&#8221;를 찾는 질문글이 하루에도 몇십개씩 올라옵니다. 하나같이 고수님이 자신의 문제를 해결해 주길 바라고 있는데, &#8220;이 문제를 해결하실 수 있는 고수님들만 보세요.&#8221; 같은 스타일의 제목이라면, 고수가 아닌 저는 답변도 달지 말라는건가요? &#8220;고수&#8221; 라는 단어가 언제부터 이렇게 흔하게 쓰였는지는 모르겠지만, 단어에 [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_359" class="wp-caption alignleft" style="width: 270px"><img class="size-full wp-image-359" title="the_professional" src="http://ufx.kr/blog/wp-content/uploads/2009/12/the_professional.jpg" alt="며칠전에 뤽 베송의 초기작 &quot;마지막 전투&quot;를 본 김에 생각나서 레옹(원제:The Professional)의 포스터를 넣어보았습니다." width="260" height="359" /><p class="wp-caption-text">며칠전에 뤽 베송의 초기작 &quot;마지막 전투&quot;를 본 김에 생각나서 레옹(원제:The Professional)의 포스터를 넣어보았습니다.</p></div>
<p>제목을 위와 같이 잡아 본건 다음과 같은 흥미로운 이야기가 곁들여져 있습니다.</p>
<p>제가 주로 활동하고 있는 <a href="http://cafe.naver.com/flashdev" target="_blank">플생사모</a>에는 &#8220;고수&#8221;를 찾는 질문글이 하루에도 몇십개씩 올라옵니다. 하나같이 고수님이 자신의 문제를 해결해 주길 바라고 있는데, &#8220;이 문제를 해결하실 수 있는 고수님들만 보세요.&#8221; 같은 스타일의 제목이라면, 고수가 아닌 저는 답변도 달지 말라는건가요?</p>
<p>&#8220;고수&#8221; 라는 단어가 언제부터 이렇게 흔하게 쓰였는지는 모르겠지만, 단어에 특별히 좋지않은 이미지가 스물스물 배어들은것 같습니다.</p>
<p>한편 제가 참여하고 있는 <a href="http://cafe.naver.com/pfgroup" target="_blank">스터디 그룹</a>의 리더인 <a href="http://wooyaggo.tistory.com/" target="_blank">우야꼬</a>군은 평소에 &#8220;고수&#8221;와 &#8220;프로&#8221;와의 구분을 이렇게 한다고 합니다.</p>
<p>고수는 엄청나 보이는 로직과 현란한 코드 테크닉으로 빠르게 프로그램을 짜고 버그를 재빨리 알아내어 순식간에 수정을 해치우는 반면, 프로는  같은 기능의 프로그램을 만들어도 코드가 훨씬 간단하고 애초부터 버그가 일어나지 않도록 프로그램을 작성한다고 합니다. (우야꼬 어록?)</p>
<p>위의 내용에서, 누군가를 가르치는 입장으로 상황으로 바꾸어 정의해 본다면,</p>
<p>고수는 자신의 뛰어난 실력을 발휘하여 학생이 무엇이 부족한지 신경쓰지 않고 어려운 테크닉을 늘어놓는 반면, 프로는 학생이 현재 무엇이 필요한지 파악하고 그것을 적절하고도 가볍게 이해시켜줍니다.</p>
<p>가장 불행한 케이스는 학생 자신도 무엇을 모르는지 조차 잘 모르는 경우와, &#8220;이건 어려운게 아닌데&#8230;&#8221; 라고 고수가 대답하는 경우 입니다. 그래서 이 시리즈 포스트의 제목에 있는 &#8220;고수&#8221; 라는 단어는 사실상 이리저리 긍정적인 의미로 사용되지 않았음을 미리 밝히는 바입니다.</p>
<p style="text-align: center;"><span id="more-347"></span>***</p>
<div id="attachment_349" class="wp-caption alignright" style="width: 210px"><img class="size-full wp-image-349" title="The_Wall_by_nbknew" src="http://ufx.kr/blog/wp-content/uploads/2009/12/The_Wall_by_nbknew.jpg" alt="이런 느낌?" width="200" height="300" /><p class="wp-caption-text">이런 느낌?</p></div>
<p>그러나 꼭 위의 이유 때문이 아니더라도 AS3.0 시작하는 사람들은 그 앞에 놓인 무언가에 탁 하고 막히는 느낌과 만나게 됩니다. 저는 그것을 &#8220;AS3.0 주위를 둘러싸고 있는 벽들&#8221; 이라고 표현을 합니다. 이 벽의 높이는 프로그램적 이론과 지식기반이 없는 디자이너 계층의 경우에 한층 높아지고, 아이러니 하게도 AS2.0을 다룰 줄 아는 사람에게 더 높게 보이는 경향이 있습니다.</p>
<p>이 시리즈는 그 높아 보이는 벽을 넘을 수 있는 수준으로 낮게 보이도록 하는 몇가지 방법을 소개하게 됩니다. (한편으로는 저의 경험담에 다름없을 것입니다.)<br />
특정한 수준에 위치한 사람이 다음 단계로 넘어갈 수 있게 도움을 주고자 하는 것이 이 포스트들의 목적이기 때문에 이 시리즈를 읽을 필요가 있는 분은 아래 분들에 한정됩니다. (이 외의 분들이 읽어주시는 것은 시간낭비가 될 가능성이 높습니다.)</p>
<ol>
<li>AS2.0 은 다룰줄 아는데 AS3.0 은 무비클립을 addEventListener 를 이용해 버튼으로 만들어 사용할 수 있는 수준.</li>
<li>온라인 강좌와 책을 읽을때는 무슨소리인지 알것 같으나, 막상 코드를 짜려고 하면 뭐부터 해야할지 막막.</li>
<li>AS3.0 코드는 fla 파일의 1프레임에만 작성해 봤을 뿐.</li>
</ol>
<p>이것은 마치&#8230; 그 예전 동네 어귀에 들어온 약장수의 멘트 같지 않습니까?<br />
어쨌건 대략 위와 같은 분들을 이 포스트 시리즈의 독자로 설정했습니다.</p>
<p>AS3.0을 공부하기로 마음먹고 이런 저런 것을 해 보는데 위에서 말한 어떤 벽에 막혀서 버둥대다가 시간을 허비하고 생업(아마도 디자인)으로 돌아가고 하는 것을 여러번 반복해본 사람들이죠. 눈치채신분들이 있을지 모르겠는데, 맞습니다. 바로 제가 그렇게 AS3.0 을 접할 기회를 몇번을 만들었음에도 불구하고 매번 벽에 막혀 시간을 허비한 사람이죠. ^^</p>
<p>그러다가 어느 특정한 시점에 이제까지 막혔던 원인이 바로 이 부분을 몰라서 라는 것을 깨닫게 됩니다. 벽에 막혔을때 누군가 관대하시고 관대하신 분이 &#8220;이 부분을 확인해 보거라&#8221; 라고 한마디만 해 줬다면, 저는 몇년의 시간을 절약하고도 남았을 것입니다.</p>
<p style="text-align: center;">***</p>
<p>그렇지만 무엇보다 중요한 것은 실제 AS3.0 으로 무엇인가는 만들어 봐야 한다는 것입니다. 제아무리 훌륭한 강좌에, 온갖 원서, 번역서를 다 떠안고 있어도 실제 만들어보지 않으면 그냥 허공으로 날아가는 지식일 뿐입니다.</p>
<p>또한 이 포스트 시리즈는 강좌가 아닙니다. 레퍼런스 스타일로 하나부터 열까지 다 나열해가며 설명하는 것이 아니라 특정한 몇가지 방법을 몰라서 겪게 되는 문제의 해결을 다루고 있습니다. 좀더 정확하게 표현하자면 &#8220;고수&#8221;들은 대수롭지 않게 생각해서 지나친 그 부분이 어떤 부분인지 알려 드립니다.</p>
<p>과연 몇 분이 각성을 해주실지, 저도 기대 되는군요.</p>
]]></content:encoded>
			<wfw:commentRss>http://ufx.kr/blog/347/feed</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>

