Skip to content

함수 표현식 과 함수 선언식

chchoing88 edited this page May 6, 2019 · 1 revision

Quick Tip: Function Expressions vs Function Declarations

번역 : https://www.sitepoint.com/function-expressions-vs-declarations/

자바스크립트는 함수 생성 방식에 대해 2가지 방법이 있다. Funtion 선언 방법은 오랫동안 사용해 왔었지만 함수 표현식은 점차 쓰여져 가고 있다.

function funcDeclaration() {
    return 'A function declaration';
}

var funcExpression = function () {
    return 'A function expression';
}

Differences between Declarations and Expressions

var 문과 유사하게 function 선언들은 다른 코드의 위로 hoist 된다. Function 표현식은 hoist 되지 않는다. 그것은 그 함수들이 선언된 스코프 이후 지역변수의 사본을 보유하는 것을 가능하게 한다.

일반적으로 함수 선언과 함수 식은 서로 바꿔 사용할 수 있지만 함수식이 임시 함수 이름없이 코드를 더 쉽게 이해할 수있는 경우가 있습니다.

Benefits of Function Expressions

함수 표현식이 함수 선언보다 더 유용하게 사용되는 몇 가지 다른 방법이 있습니다.

  • 클로저로서
  • 다른 함수의 인자로서
  • 함수 표현식의 즉시 실행으로서 (IIFE)

Creating Closures

클로저는 함수가 실행되기 전에 함수에 매개 변수를 제공하려는 경우에 사용됩니다. 이것이 NodeList를 루프 할 때 어떻게 유익한 지 보여주는 좋은 예가 있습니다. 클로저를 사용하면 함수가 실행될 때 해당 정보를 더 이상 사용할 수없는 경우 인덱스와 같은 다른 정보를 유지할 수 있습니다.

function tabsHandler(index) {
    return function tabClickEvent(evt) {
        // Do stuff with tab.
        // The index variable can be accessed from within here.
    };
}

var tabs = document.querySelectorAll('.tab'),
    i;

for (i = 0; i < tabs.length; i += 1) {
    tabs[i].onclick = tabsHandler(i);
}

연결된 이벤트 핸들러는 나중에 루프가 완료된 후 실행되므로 for 루프의 적절한 값을 유지하려면 클로저가 필요합니다.

// Bad code, demonstrating why a closure is needed
var i;

for (i = 0; i < list.length; i += 1) {
    document.querySelector('#item' + i).onclick = function doSomething(evt) {
        // Do something with item i
        // But, by the time this function executes, the value of i is always list.length
    }
}

for 루프에서 doSomething () 함수를 추출하면 문제가 발생하는 이유를 더 쉽게 이해할 수 있습니다.

// Bad code, demonstrating why a closure is needed
var list = document.querySelectorAll('.item'),
    i,
    doSomething = function (evt) {
        // Do something with item i.
        // But, by the time this function executes, the value of i is not what it was in the loop.
    };

for (i = 0; i < list.length; i += 1) {
    item[i].onclick = doSomething;
}

여기의 해결책은 인덱스를 함수 인수로 외부 함수에 전달하여 해당 값을 내부 함수로 전달할 수 있도록하는 것입니다. 일반적으로 내부 반환 함수에 필요한 정보를 구성하는 데 사용되는 처리기 함수를 볼 수 있습니다.

// the following is good code, demonstrating the use of closure

var list = ['item1', 'item2', 'item3'],
    i,
    doSomethingHandler = function (itemIndex) {
        return function doSomething(evt) {
            // now this doSomething function can retain knowledge of
            // the index variable via the itemIndex parameter,
            // along with other variables that may be available too.
            console.log('Doing something with ' + list[itemIndex]);
        };
    };

for (i = 0; i < list.length; i += 1) {
    list[i].onclick = doSomethingHandler(i);
}

클로저의 다른 좋은 예와 도움이되는 방법은 다음에서 찾을 수 있습니다.closure examples FAQ

Passing as Arguments

함수 표현식은 중간 임시 변수에 지정하지 않고 직접 함수에 전달할 수 있습니다.

익명 함수의 형태로 jQuery에서 자주 볼 수 있습니다. 예를 들면 다음과 같습니다.

$(document).ready(function () {
    console.log('An anonymous function');
});

또한 forEach ()와 같은 메서드를 사용할 때 배열 표현식을 처리하는 데 함수식이 사용됩니다. 익명 함수가 이름을 가지지 못하지는 않습니다. 함수 표현식의 이름을 지정하여 함수가 수행해야하는 것을 표현하고 디버깅을 돕는 것이 좋습니다.

var productIds = ['12356', '13771', '15492'];

productIds.forEach(function showProduct(productId) {
    ...
});

Immediately Invoked Function Expressions (IIFE)

IIFE는 함수와 변수가 전역 범위에 영향을 미치지 않도록 도와줍니다. 모든 속성은 익명의 함수로 범위가 지정됩니다. 이는 코드가 원치 않는 또는 원하지 않는 부작용을 다른 곳에서가지는 것을 방지하는 데 사용되는 일반적인 디자인 패턴입니다.

또한 섹션을 유지하기 쉽도록 코드 블록을 포함하는 모듈 패턴으로 사용됩니다. JavaScript 클로저, 콜백 및 IIFE 이해하기에서 ( Demystifying JavaScript closures, callbacks and IIFEs ) 이것에 대해 자세히 살펴 봅니다.

IIFE의 간단한 예는 다음과 같습니다.

(function () {
    // code in here
}());

모듈로 사용하면 코드에 대한 유지 관리가 쉽습니다.

var myModule = (function () {
    var privateMethod = function () {
        console.log('A private method');
    },
    someMethod = function () {
        console.log('A public method');
    },
    anotherMethod = function () {
        console.log('Another public method');
    };

    return {
        someMethod: someMethod,
        anotherMethod: anotherMethod
    };
}());

결론

지금까지 보았 듯이 함수 표현식은 함수 선언으로는 얻을 수없는 많은 것을 제공하지는 않지만 함수 선언을 사용하면 더 명확하고 읽기 쉬운 코드가 될 수 있습니다. 이들이 광범위하게 사용되면 모든 개발자의 도구 상자에 필수 요소가됩니다. 위에서 언급하지 않은 흥미로운 방식으로 코드에서 함수 표현식을 사용합니까? 댓글을 달아서 알려주세요.

Clone this wiki locally