Self-Executing Anonymous Functions (자가 실행 익명 함수)

프론트앤드/JavaScript 2016. 6. 25. 01:25 by kira-master

When learning JavaScript, with all the attention given to variables, functions, 'if' statements, loops and event handlers, often little is done to educate you on how you might cleanly organise your code into a cohesive, structurally-sound whole.

자바 스크립트를 배우면서 변수, 함수, if , 반복 그리고 이벤트 핸들러에 관심을 갖다 보면, 아마도 당신은 깔끔하게 당신의 코드가 전체적으로 응집도가 있고 , 아주 구조적으로 구성해야 하는지에 대해서 교육을 받게 됩니다. ,

Let's take the following code for example:

다음과 같은 코드를 예로 들어 봅시다.

 

var foo = 'Hello';
var bar = 'World!';

function baz(){
return foo + ' ' + bar;
}

console.log(baz());

 

 

 

This style of code looks quite normal, works fine and doesn't cause any problems. At least for now.

코드 스타일은 아주 평범합니다, 작동도 아주 잘되고 어떤 문제를 일으키지는 않습니다. 적어도 지금은 말이죠.

This style of code, when implemented in a large application, can start to become an unwieldy mess. The global namespace becomes littered with functions and variables, all tenuously linked to each other through a combination of rudimentary comments and potentially unspoken developer knowledge.

코드의 스타일로 거대한 어플리케이션에 구현되면 거추장스러운 상태로 되기 시작합니다. 전역 네임스페이스는

The first step on the journey to beautiful, modular JavaScript is to learn the art of the self-executing anonymous function.


(function(){
console.log('Hello World!');
})();

 

 

Let's look at this carefully. This code is made up of two key parts.

주위 깊게 보세요, 코드는 2가지 핵심적인 부분이 있습니다.

First is the anonymous function:

첫째는 익명 함수 입니다.

 


(function(){
//Normal code goes here
})

 

 

 

The really interesting part is what happens when we add this right at the end:

정말로 흥미로운 것은 우리가 아래 코드를 끝에 추가할 어떤 일이 일어난다는 것이다.

 

 

();

 

 

 

Those two little brackets cause everything contained in the preceding parentheses to be executed immediately. What's useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function aren't available to the code outside of it, effectively using closure to seal itself from the outside world.

두개의 소괄호는 이전 괄호에 포함된 모든 것을 즉시 실행되게 한다. 이것의 유용 함은 자바스크립트에서 함수 수준 범위를 가진다는 것에 있다.

익명 함수 이내의 모든 변수, 함수들은 익명 함수 밖에 코드에 접근할 없고, 이것은 효과적으로 외부 영역으로부터 익명 함수를 감싸서 막는 것이다.

Let's apply this design patten to our gloriously inane example code.

우리의 아주 화려하게 초라한 예제 코드에 디자인 패턴을 적용해보자.

 



(function(){
var foo = 'Hello';
var bar = 'World!'

function baz(){
return foo + ' ' + bar;
}
})();

//These all throw exceptions:
console.log(foo);
console.log(bar);
console.log(baz());

 

 

The last three lines throw exceptions because currently nothing is accessible outside the anonymous function. To allow access to a variable or function, we need to expose it to the global 'window' object.

현재 어떤 것도 익명 함수 내부에는 접근할 없기 때문에 밑에서 3번쨰 라인에서 에러가 난다. 변수 또는 함수를 접근을 허용하기 위해서는, 우리는 글로벌 window 객체에 익명 함수를 노출하는 것이 필요한다.

 



(function(){
var foo = 'Hello';
var bar = 'World!'

function baz(){
return foo + ' ' + bar;
}

window.baz = baz; //Assign 'baz' to the global variable 'baz'...
})();

console.log(baz()); //...and now this works.

//It's important to note that these still won't work:
console.log(foo);
console.log(bar);

 

One of the major benefits of this pattern, as seen on the last two lines of the previous example, is that you can limit access to variables and functions within your closure, essentially making them private and only choosing to expose an API of your choice to the global scope.

패턴의 주된 이점 중에 하나는 , 예제에서 밑에서 2번째 라인을 보면 , 당신의 클로져 내부의 변수, 함수들에 대한 접근을 제한시킬 있고 , 기본적으로 Private 하면서 , 오직 global 영역에 당신의 선택에 의한 API들을 노출시키는 것을 선택할 있다.

One popular spin on this design pattern, which can be seen in the jQuery source, is to pass in some commonly used objects. In our code we reference 'window', so let's pass that in as a parameter to the anonymous function.

제이쿼리에서도 있었던 것처럼, 디자인 패턴의 하나의 일반적인 흐름은 공통적으로 공통적으로 객체를 사용하여 넘기는 것이다. 우리가 참조한 WINDOW 우리 코드에서 , 익명함수의 파라미터로 넘겨보자.

 

 



(function(window){
var foo = 'Hello';
var bar = 'World!'

function baz(){
return foo + ' ' + bar;
}

//In this context, 'window' refers to the parameter
window.baz = baz;
})(window); //Pass in a reference to the global window object

 

 

 

 

When minifying your code, this design pattern will yield great results. All references to 'window' in your code can be renamed to 'a', for example:

당신의 코드를 축소할 , 디자인 패턴은 아주 좋은 결과를 가져온다. 당신의 코드에서 Window 대한 모든 참조들은 아래 예처럼 a 새롭게 이름을 바꿀 있다..

 

(function(a){
console.log(a === window); //Returns 'true'
})(window);

 

 

Normally you'll want to pass in a few objects. A technique you can see used within jQuery itself is to reference an extra parameter that isn't defined when the anonymous function is executed, in effect creating an alias for 'undefined':

일반적으로 당신은 개의 객체를 넘기는 원한다. 제이쿼리 자체에서 사용한 기술을 보면, 익명 함수가 실행될 효과적으로 undefined alias 만들면서 여분의 파라미터를 참조하는 것이다.

 


(function(window, document, $, undefined){
var foo;
console.log(foo === undefined); //Returns 'true'
})(window, document, jQuery);

 

 

You may have noticed that the previous example also aliased 'jQuery' to '$', allowing it to play nicely with other frameworks without having to use jQuery in noConflict mode.

It's worth pointing out that the parameter names are purely for convention. The following code would work equally as well and serves as a great illustration of what's really going on in this design pattern:

충돌 모드를 사용하지 않고도 다른 프레임워크들과 문제 없이 동작하도록 해주는 이전 예시에서 jQuery 또는 $ rename 했다는 것을 알아차릴 있다.

It's worth pointing out that the parameter names are purely for convention. The following code would work equally as well and serves as a great illustration of what's really going on in this design pattern:

이것은


(function(mark, loves, drinking, coffee){
mark.open('http://www.google.com'); //window
loves.getElementById('menu'); //document
drinking('#menu').hide(); //jQuery
var foo;
console.log(foo === coffee); //undefined
})(window, document, jQuery);

 

 

 

Although, for obvious reasons, I advise against this ;)

The benefits of this design pattern will become even more apparent in later posts. Harnessing the power of self-executing anonymous functions will allow you to create more complex but ultimately more intuitive code structures that will make your larger projects much easier to manage.

'프론트앤드 > JavaScript' 카테고리의 다른 글

자바스크립트 함수  (0) 2016.02.21

자바스크립트 함수

프론트앤드/JavaScript 2016. 2. 21. 17:58 by kira-master

1. 자바 스크립트 함수

    1.1 자바스크립트 함수

        - function 이란 first-class object 이다.

        - first-class object 란?

first-class object는 변수에 저장할 수 있어야 합니다.

first-class object는 함수의 파라미터로 전달할 수 있어야 합니다.

first-class object는 함수의 반환값으로 사용할 수 있어야 합니다.

first-class object는 자료 구조에 저장할 수 있어야 합니다.

        

    

2. 함수의 선언과 표현식

2.1 Function Declaration

         - 함수 선언은 실행 가능한 코드 블록이 아니라 함수의 정의 하는 문장이다.

        - 함수 선언 코드 자체는 실행되지 않는다.

    2.2 Function Expression

- function Expression 은 함수 리터럴로 실행 가능한 코드로 해석되어 변수에 할당되어 있음을 의미한다.

        - 또는 ( )를 사용하여 함수를 감싸준다. 이를 Self invoking Function이라고 한다.

        - Self invoking Function은 해석과 동시에 실행되는 코드 블럭을 말한다.

3. 예제

    3.1

    Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

foo(); // success !

//Function Declarations

function foo() {

    alert('foo');

}

foo(); // foo is not defined.

// Function Expressions ,  anonymous function expression

var foo = function (){

    alert('foo');

};

//named function expression

var foo = function foo() {

    alert('hello');

};

// 자기호출함수는 해석과 동시에 실행되는 코드블럭을 말한다.

// self invoking function expression

(function foo() {

   console.log('hello');

})();

 

    3.2

AngularJs 1일차

프론트앤드/AngularJS 2016. 2. 20. 15:39 by kira-master

 

1. Ionic Framework설치

 

1-1. JDK 1.7 설치, Ant,Android SDK 설치

    - http://www.oracle.com/technetwork/java/javase/downloads/index.html

- http://developer.android.com/sdk/index.html

- http://ant.apache.org/

- 설치 후 환경 변수 자바 JDK Path 추가

 

- JAVA_HOME으로 시스템 변수 추가

 

- PATH 에 JAVA_HOME\bin 추가

 

- ClassPath 위와 같이 추가

 

- Apache-Ant 를 다운 받아 C:\ 에 압축해체를 한다.

- ANT_HOME을 추가한다.

 

- Path 에도 동일하게 추가한다.

 

- Android_SDK 변수 추가

- ;%Android_SDK%\platform-tools; 추가

- ;%Android_SDK%\tools; 추가

 

- cmd 창에서 다음 명령어로 정상적으로 Path 가 잡혀 있는지 확인

- java –version

- javac

- ant –version

- android // SDK 매니저가 실행됨

 

1-2. Node.js 설치

- https://nodejs.org/en/download/

- 각 OS 버전 별로 설치한다.

 

1-3. 개발 도구

    - https://atom.io

    - 필자의 경우 아톰 에디터를 이용했다. 취향 별로 ….

 

1-4. NPM에서 설치

    - NodeJs에서 NPM(Node Packaged Modules)으로 Ionic framework 설치

    - C:\>npm list -g --depth=0

C:\Users\bb\AppData\Roaming\npm

├── cordova@5.4.1

└── ionic@1.7.12

    - npm list –g –depth // 현재 설치된 모듈 리스트 정보를 가져옴    

    - npm install -g cordova // -> 코도바 설치(하이브리드앱 변환 라이브러리)

    - npm install -g ionic // -> cordova를 좀더 사용하기 편하게 만든 UI 템플릿을 제공한다.

 

 

2. Ionic project 시작하기

 

    2.1 프로젝트 만들기

        - C:\app001>ionic start app // 만들고 싶은 폴더 위치에서 app(앱의이름)을 지정해주면 프로젝트 생성

    

        - CMD 창에서 프로젝트 생성 메시지가 뜨고 명령어에 대한 팁이 나온다.

    

 

    2.2 프로젝트 실행하기

        - 해당 app 폴더로 이동한 후에

- $ionic serve // 내장서버로 app 실행

        

        - 실행 모습

        

3. lonic project 빌드하기

    3.1

 

'프론트앤드 > AngularJS' 카테고리의 다른 글

Ionic 으로 초심자 개발 시작하기 ..2일차  (0) 2016.01.17
Ionic 으로 초심자 개발 시작하기 ..  (0) 2016.01.16
01. AngularJS  (0) 2015.12.28

Ionic 으로 초심자 개발 시작하기 ..2일차

프론트앤드/AngularJS 2016. 1. 17. 14:09 by kira-master

ionic으로 개발하면서 느낀건데 수업시간때 제이쿼리 모바일처럼

앱 UI 템플릿을  제공하지만 앵귤러 Js 에 맞물려서 설계된게 마음에 들었다.

보통 프론트앤드 소스 보면 모듈화가 기능별로는 잘 안 되어있고 보통 한 소스로 묶어서 JS 라이브러리로 만들어져 있거나

한 파일에 몰아서 엄청난 양의 소스 라인을 자랑한다.

도처히 백앤드를 주로 해봤던 나에게는 정말 너무 싫다.

그러던 중 앵귤러의 모듈형 개발 방식은 너무나도 마음에 드는 방식이다.

지금의 프론트앤드는 춘추전국시대이기 때문에 다양한 기술과 개발 방식이 난잡하게 있고 

발전 속도가 미친듯이 빠르기 때문에 개발을 표준화 시키는 기술이나 방식은 정말 중요한것 같다.


아무리 언어랑 기술이 발전해도 기본적인 비지니스 로직이나 효율적인 설계 방식은 

어는 정도 과거 선배님들의 노고로 많이 모답 답안들도 많고....

실제 그런 효율적인 방식이 집약된 여러가지 웹 프레임워크의 등장으로 

내부적으로 설계된 개발 방식이나 아키텍처의 내용들을 살펴볼수 있어서 참 좋은것 같다.


단점은 공부할게 많다는 것이다 ! ^^ 하지만 프로그래밍의 매력은 배울수록 구현할수 있는 영역의 늘어남이 아니던가? 

배울수록 나는 자유롭게 놀수 있다는 것이 매력이 나를 신기술로 자꾸 빠져든게 한다.




---- 아래는 아이오닉 웹 문서 안내다. 어제는 앱 만들어서 간단하게 UI 를 맛 보았다.

http://ionicframework.com/docs/components/   // 이 주소는 아이오닉 프레임워크 컴포넌트들이다.

Quick Start

A guide to quickly get up and running with Ionic.io


 Note

Getting started with the Ionic Platform is incredibly easy, so this guide is intentionally very simple. However, if something doesn't make sense, or you find yourself wanting more information about each step, head over to our Setup guide.


First, make sure you have signed up for an Ionic Platform account.

1. CREATE AN APP

$ ionic start APPNAME
$ cd APPNAME

2. ADD THE PLATFORM WEB CLIENT

$ ionic add ionic-platform-web-client

3. TELL IONIC ABOUT YOUR APP

$ ionic io init

4. INTEGRATE A SERVICE







http://learn.ionicframework.com/ 아이오닉을 튜토리얼을 동영상을 보고 연습할수 있게 했다.


'프론트앤드 > AngularJS' 카테고리의 다른 글

AngularJs 1일차  (0) 2016.02.20
Ionic 으로 초심자 개발 시작하기 ..  (0) 2016.01.16
01. AngularJS  (0) 2015.12.28

Ionic 으로 초심자 개발 시작하기 ..

프론트앤드/AngularJS 2016. 1. 16. 09:11 by kira-master


2016년 1월 16일 -> 여러 회사에서 면접 후 안드로이드 스킬이 부족함을 꺠닫고
                     여러 커뮤니티 분들의 조언을 얻어서 ionic으로 하이브리드앱 제작에 도전을 시작함.

참고 자료

http://www.slideshare.net/ssusercf5d12/ionic-1  // 한성일 님 자료

https://nodejs.org/en/ -> node-v5.4.1-x64.msi    // 다운로드 설치 

개발툴 

https://atom.io/ // Atom 에디터 사용  




// 윈도우 8 기준 nodejs 용 commend 창에서 작업함
npm install -g cordova // -> cordova 수업 시간때 배운거 안드로이드 자바 객체로 감싸줌
npm install -g ionic // -> cordova를 좀더 사용하기 편하게 만든 UI 템플릿을 제공한다.

https://www.youtube.com/watch?v=15daTaDQ6Yg -> ionic 웹 시작할떄 사용법 안내 회원가입하고 로그인 해야지 되나봄 (설명은 영어임 ㅋㅋ )



아이오닉 쓰는것 까지 좋았는데 다시 angularjs에서 막힌다. 

앵귤러 쓰면서 느낌건데 거의다 자바스크립트 배열 자료로 설정값 넣어주면 자동으로 돌아가는 구조인것같다.
아직 개념적으로 아키텍처를 완벽하게 이해하지는 못해서 계속 쓰면서 공부해야겠다.


angularjs 공부하면서 찾은 사이트이다

http://iotschool.tistory.com/163 

링크로 가면 GDG에서 어떤 분이 발표하신것 봤는데 참 쉽게 설명했다. 

나머지 동영상은 외국인 분이 블라블라 하신다.

아 ㅋㅋㅋ미치겠다 ...

'프론트앤드 > AngularJS' 카테고리의 다른 글

AngularJs 1일차  (0) 2016.02.20
Ionic 으로 초심자 개발 시작하기 ..2일차  (0) 2016.01.17
01. AngularJS  (0) 2015.12.28

1. 시작하기

프론트앤드/ReactJs 2016. 1. 5. 22:35 by kira-master

Getting StartedEdit on GitHub

JSFiddle

The easiest way to start hacking on React is using the following JSFiddle Hello World examples:

Using React from npm (NPM 사용하여 설치하기) 

We recommend using React with a CommonJS module system like browserify or webpack. Use the react and react-dom npm packages.

// main.js
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

To install React DOM and build your bundle with browserify:

$ npm install --save react react-dom babelify babel-preset-react
$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js

To install React DOM and build your bundle with webpack:

$ npm install --save react react-dom babel-preset-react
$ webpack

Note:

If you are using ES2015, you will want to also use the babel-preset-es2015 package.

Quick Start Without npm(NPM 없는 빠른 시작)

If you're not ready to use npm yet, you can download the starter kit which includes prebuilt copies of React and React DOM.

In the root directory of the starter kit, create a helloworld.html with the following contents.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

The XML syntax inside of JavaScript is called JSX; check out the JSX syntax to learn more about it. In order to translate it to vanilla JavaScript we use <script type="text/babel">and include Babel to actually perform the transformation in the browser.

Separate File

Your React JSX code can live in a separate file. Create the following src/helloworld.js.

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

Then reference it from helloworld.html:

<script type="text/babel" src="src/helloworld.js"></script>

Note that some browsers (Chrome, e.g.) will fail to load the file unless it's served via HTTP.

Offline Transform

First install the Babel command-line tools (requires npm):

npm install --global babel-cli
npm install babel-preset-react

Then, translate your src/helloworld.js file to plain JavaScript:

babel --presets react src --watch --out-dir build

Note:

If you are using ES2015, you will want to also use the babel-preset-es2015 package.

The file build/helloworld.js is autogenerated whenever you make a change. Read theBabel CLI documentation for more advanced usage.

ReactDOM.render(
  React.createElement('h1', null, 'Hello, world!'),
  document.getElementById('example')
);

Update your HTML file as below:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <!-- No need for Babel! -->
  </head>
  <body>
    <div id="example"></div>
    <script src="build/helloworld.js"></script>
  </body>
</html>

Next Steps

Check out the tutorial and the other examples in the starter kit's examples directory to learn more.

We also have a wiki where the community contributes with workflows, UI-components, routing, data management etc.

Good luck, and welcome!

01. AngularJS

프론트앤드/AngularJS 2015. 12. 28. 15:53 by kira-master

1. AngularJS 핵심 컴포넌트 정리 


Module 

모듈은 일종의 컨터이너 역할을 한다.


Config

어플리케이션이 실행되기 전에 설정을 관리


Routes 

라우트는 어플리케이션의 특정 상태로 이동하는 경로를 정의하기 위한 개념이다.


Views 

모든 자바스크립트와 함께 DOM을 컴파일하고 렌더링 한 이후에 생성된다.


$Scope

AngularJS 어플리케이션 내부에서 뷰와 컨트롤러를 결합하는 객체이다.



Controller

컨트롤러는 뷰가 바인딩하고 있는 속성과 메서드를 정의하기 위한 객체다.



Directive

디렉티브는 View에 대한 확장 기능이다. 디렉티브를 이용해 원하는 동작을 캡슐화한 

재사용 가능한 사용자 정의 요소를 정의 할수 있다.


Service  

AugularJS 어플리케이션의 공통 기능을 구현하기 위한 컴포넌트이다.


2. 

Nav