ACE-T's JS Part 04. 익명함수!

2014. 7. 3. 17:31Front/JavaScript

반응형

요즘 gis를 하는데 있어서...아래의 형태가 있었습니다. 음..조금 당황 했습니다. ㅋㅋㅋ;; 많이 써보는 형태는 아니였던게죠..ㅠ.ㅠ..

anyways..이제부터 알아가보도록 하겠습니다.^-^

(function(){


})();



참고 사이트  http://www.nextree.co.kr/p4150/    

KSUG 최영목님이 댕기시는 회사에 너무 잘 정리를 해놔서..참고 하였습니다. 넥스트리 화이팅! ㅎㅎ


보통 함수 선언을할 때 아래와 같이 합니다.


이것은 함수 선언식이라고 부릅니다.

function acetBlog(){

   /* 실행코드 */

}


하지만 아래와 같이! 선언할 수 있습니다. 함수 표현식과 즉시실행함수 가 있습니다. 당황하지 마세요! 이제부터 알아가면 되니깐요! ㅎ

함수 정의할 때 “함수는 first-class object이므로 변수에 할당될 수 있다.” 라는 전제 하에 아래와 같이 작성할 수 있습니다.

제가 보았던

(function(){


})();

이친구는 5번 이였군요! ㅎㅎㅎ


왜 이런식으로 작성하는 걸까요???

간단히 생각해보면..

자바스크립트의 동작 아키텍처를 정확히는 모르겠지만 함수선언식과 함수표현식의 큰 차이는??

함수 선언식 :  스크립트 로딩시에 VO에 함수를 저장!

함수 표현식 : 런타임시에 해석되고 실행! VO에 함수 저장 X

um..클락포드 형님 책에 분명히 나왔던 것 같은데...이 내용을 알고 보았다면 더더욱 재밌고 이해가 더 잘되었을 것 같네요 ㅎㅎ

그리고 함수 선언식이 많으면 많을 수록 VO에 함수를 저장하고 하면 처리에서 느려질 것 입니다.


자! 이제 함수 표현식 친구들을 만나보겠습니다.

우선 아래를 읽어 봅시다. 고개를 끄덕끄덕 거리는 모습이 눈에 선하네요~저만 그런가요ㅋㅋ;;

자바스크립트에서 가장 큰 문제점 중의 하나는 글로벌 스코프에 정의된 것은 코드 내의 어디서든지 접근이 가능하다는 것입니다. 하지만, 외부에 공유되면 안되거나 공유될 필요가 없는 속성이나 메소드가 있습니다. 또한, 다른 스크립트 파일 내에서 동일한 이름으로 명명된 변수나 함수가 있을 경우 원치 않는 결과를 가져올 수 있습니다.


우선 코드를 하나 보겠습니다.

결과는 아래와 같습니다.


코드 : 익명 함수표현식(anonymous function expression)

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

var app = function(){


console.log("Hi~~~~test01");

}


app();


</script>


    </head>


<body>

This is function expresstion TEST!


</body>

</html>



즉시 실행함수를 한번 살펴보겠습니다.

결과 test01.html과 같은 결과가 나옵니다. Good!


단, 함수표현식은 함수를 정의하고, 변수에 함수를 저장하고 실행하는 일련의 과정을 거칩니다.  하지만, 즉시실행함수를 사용하면 이와 같은 과정을 거치지 않고 즉시 실행된다는 특징이 있습니다.


코드 :

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

(

                          function(){

console.log("Hi~~~~test02");

  }()

                        );


</script>


    </head>


<body>

This is function expresstion TEST!


</body>

</html>  



변수를 하나 할당하고 즉시 실행함수를 호출 해보겠습니다.
결과 : 결과는 console에 private라고 찍힙니다.

코드 : 아래의 코드에서 가장 눈여겨 볼 부분은 app.prop 이부분 입니다.  
연결고리들이 보이시나요?  app - prop - privateVar - 'private'

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

var app = (function() {

   

       var privateVar = 'private';

   

       return {

        prop : privateVar

       };


       }());


                       // 함수에 포함되지 X

       console.log(app.prop); // "private" 출력


</script>


    </head>


<body>

This is function expresstion TEST!


</body>

</html>


즉시실행함수 내부의 변수 privateVar를 접근한 것입니다. 자바스크립트의 변수는 함수내의 scope를 가집니다. 그런데 외부에서 접근을 한 것
입니다. 와우!! 아래를 읽어보세요!~~

이와 같이, 즉시실행함수는 변수의 스코프를 포함하는데 사용되며 외부에서 함수 내의 변수에 접근할 경우 이를 통제할 수 있습니다. 즉시실행함수는 글로벌 네임스페이스에 변수를 추가하지 않아도 되기 때문에 코드 충돌이 없이 구현할 수 있어 플러그인이나 라이브러리 등을 만들 때 많이 사용됩니다.


다음으로는! 기명 함수표현식과 즉시실행 함수에 파라미터 넘겨주기 입니다.


결과 :



코드 :

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

 

                       // 기명 함수표현식

var buyCar = function(carName) {

   // I Buy a sonata1. This is good Car!. 출력

   console.log('I Buy a ' + carName + '. This is good Car!.');

};

buyCar('sonata1');

 

                        // 즉시 실행함수!

(function(carName) {

   // I Buy a sonata2. This is good Car!.출력

   console.log('I Buy a ' + carName + '. This is good Car!.');

}('sonata2'));


</script>


    </head>


<body>

This is function expresstion TEST!


</body>

</html>



마지막으로 오픈소스의 소스 내용을 한번 보겠습니다.

코드 : 아래의 소스는 html에서 <script type="text/javascript" src="./js/Taeha/AcetGISMain.js"></script> 의 내용이라고 가정하면

   jsFiles = [

                "AcetMap.js",

                "GISConstant.js",

                "GISModeState.js"

               

            ]; // etc.


에 원하는 js를 넣어두면 자동으로 js가 선언이 되어집니다. 와우! 유용한 것 같아요! ㅎㅎㅎ 

그리고..소스를 보면 지금까지 배웠던 내용들이 눈에 보이면 OK! 입니다. 

홧팅2


/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for  

* full list of contributors). Published under the 2-clause BSD license.

 * See license.txt in the OpenLayers distribution or repository for the

 * full text of the license. */


/* 

 * @requires OpenLayers/BaseTypes.js

 * @requires OpenLayers/Lang/en.js

 * @requires OpenLayers/Console.js

 */

 

/*

 * TODO: In 3.0, we will stop supporting build profiles that include

 * OpenLayers.js. This means we will not need the singleFile and scriptFile

 * variables, because we don't have to handle the singleFile case any more.

 */


(function() {

    /**

     * Before creating the OpenLayers namespace, check to see if

     * OpenLayers.singleFile is true.  This occurs if the

     * OpenLayers/SingleFile.js script is included before this one - as is the

     * case with old single file build profiles that included both

     * OpenLayers.js and OpenLayers/SingleFile.js.

     */

    var singleFile = false;

    

    /**

     * Relative path of this script.

     */

    var scriptName = "AcetGISMain.js";


    /*

     * If window.OpenLayers isn't set when this script (OpenLayers.js) is

     * evaluated (and if singleFile is false) then this script will load

     * *all* OpenLayers scripts. If window.OpenLayers is set to an array

     * then this script will attempt to load scripts for each string of

     * the array, using the string as the src of the script.

     *

     * Example:

     * (code)

     *     <script type="text/javascript">

     *         window.OpenLayers = [

     *             "OpenLayers/Util.js",

     *             "OpenLayers/BaseTypes.js"

     *         ];

     *     </script>

     *     <script type="text/javascript" src="../lib/OpenLayers.js"></script>

     * (end)

     * In this example OpenLayers.js will load Util.js and BaseTypes.js only.

     */

    var jsFiles = null;


    var getBitGISScriptLocation = function(){

        var r = new RegExp("(^|(.*?\\/))(" + scriptName + ")(\\?|$)"),

                s = document.getElementsByTagName('script'),

                src, m, l = "";

            for(var i=0, len=s.length; i<len; i++) {

                src = s[i].getAttribute('src');

                if(src) {

                    m = src.match(r);

                    if(m) {

                        l = m[1];

                        break;

                    }

                }

            }


            return l;


    }


    


    /**

     * OpenLayers.singleFile is a flag indicating this file is being included

     * in a Single File Library build of the OpenLayers Library.

     * 

     * When we are *not* part of a SFL build we dynamically include the

     * OpenLayers library code.

     * 

     * When we *are* part of a SFL build we do not dynamically include the 

     * OpenLayers library code as it will be appended at the end of this file.

     */

    if(!singleFile) {

        if (!jsFiles) {

            jsFiles = [

                "AcetMap.js",

                "GISConstant.js",

                "GISModeState.js"

               

            ]; // etc.

        }


        // use "parser-inserted scripts" for guaranteed execution order

        // http://hsivonen.iki.fi/script-execution/

        var scriptTags = new Array(jsFiles.length);

        var host = getBitGISScriptLocation() + "lib/";

        for (var i=0, len=jsFiles.length; i<len; i++) {

            scriptTags[i] = "<script src='" + host + jsFiles[i] +

                                   "'></script>"; 

        }

        if (scriptTags.length > 0) {

            document.write(scriptTags.join(""));

        }

    }

})();



이제 궁금증이 풀렸으니 소스를 보러~~여기 까지 포스팅 합니다! ㅎㅎ 다음에 또 만나요! 더 자세한 내용은 넥스트리를 방문해주세요^0^

이 포스팅은 자바스크립트 제대로 배우기 커뮤니티에 올라갑니다.

 https://www.facebook.com/groups/learnjsproperly/


참고 :


2014/04/24 - [Script/JavaScript] - ACE-T's JS_Part 01. 자바스크립트를 배운다는 것은??


2014/05/08 - [Script/JavaScript] - ACE-T's JS_Part 02. Style과 Event 다루기!!


2014/05/10 - [Script/JavaScript] - ACE-T's JS Part 03. Jquery 기초를 배워봅시다!


    - END -

반응형