program story

자바 스크립트 중첩 함수

inputbox 2020. 9. 9. 07:58
반응형

자바 스크립트 중첩 함수


내가 이해하지 못하는 자바 스크립트 코드가 있습니다.

function dmy(d) {
    function pad2(n) {
        return (n < 10) ? '0' + n : n;
    }

    return pad2(d.getUTCDate()) + '/' +
       pad2(d.getUTCMonth() + 1) + '/' +
       d.getUTCFullYear();
}

function outerFunc(base) {
    var punc = "!";

    //inner function
    function returnString(ext) {
       return base + ext + punc;
    }

    return returnString;
}

다른 함수 내에서 함수를 어떻게 정의 할 수 있습니까? my () 함수 외부에서 pad2 ()를 호출 할 수 있습니까?

불 좀 켜주세요. 감사


함수는 JavaScript의 또 다른 유형의 변수입니다 (물론 약간의 뉘앙스 포함). 다른 함수 내에서 함수를 만들면 변수의 범위를 변경하는 것과 같은 방식으로 함수의 범위가 변경됩니다. 이는 전체 글로벌 네임 스페이스 오염을 줄이기 위해 클로저와 함께 사용하는 데 특히 중요합니다.

다른 함수 내에 정의 된 함수는 함수 외부에서 액세스 할 수있는 객체에 연결되어 있지 않으면 함수 외부에서 액세스 할 수 없습니다.

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

이 예제에서 baz 함수는 foo함수가 재정의되었으므로 함수가 실행 된 후에 사용할 수 있습니다 window.baz. bar 함수는 foo함수 내에 포함 된 범위 이외의 컨텍스트에서 사용할 수 없습니다 .

다른 예로서 :

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

Fizz함수는 생성자로 설계되어 실행시 buzz새로 생성 된 객체에 함수를 할당 합니다.


폐쇄 라고 합니다.

기본적으로 다른 함수 내에 정의 된 함수는이 함수 내에서만 액세스 할 수 있습니다. 그러나 결과로 전달되고이 결과가 호출 될 수 있습니다.

매우 강력한 기능입니다. 여기에서 자세한 설명을 볼 수 있습니다.

Archive.org의 javascript_closures_for_dummies.html 미러


function x() {}

다음과 동등하거나 매우 유사합니다.

var x = function() {}

내가 착각하지 않는 한.

So there is nothing funny going on.


Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

When you declare a function within a function, the inner functions are only available in the scope in which they are declared, or in your case, the pad2 can only be called in the dmy scope.

All the variables existing in dmy are visible in pad2, but it doesn't happen the other way around :D


It's perfectly normal in Javascript (and many languages) to have functions inside functions.

Take the time to learn the language, don't use it on the basis that it's similar to what you already know. I'd suggest watching Douglas Crockford's series of YUI presentations on Javascript, with special focus on Act III: Function the Ultimate (link to video download, slides, and transcript)

참고URL : https://stackoverflow.com/questions/7295634/javascript-nested-function

반응형