JavaScript 嵌套函数

发布于 2024-12-02 19:53:06 字数 539 浏览 1 评论 0原文

我得到了一段我不明白的 javascript 代码:

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;
}

How can a function be Define inside another function?我们可以从 my() 函数外部调用 pad2() 吗?

请在上面放一些光。谢谢

I got a piece of code for javascript which I just do not understand:

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;
}

How can a function be defined within another function? Can we call pad2() from outside of my() function?

Please put some light on it. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

晚风撩人 2024-12-09 19:53:06

函数是 JavaScript 中的另一种类型的变量(当然有一些细微差别)。在另一个函数中创建函数会更改该函数的范围,就像更改变量的范围一样。这对于与闭包一起使用以减少全局命名空间污染尤其重要。

在另一个函数中定义的函数将无法在函数外部访问,除非它们已附加到可在函数外部访问的对象:

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

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

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

在此示例中,baz 函数将在 foo 函数已运行,因为它已被覆盖 window.baz。除了 foo 函数中包含的作用域之外,bar 函数不可用于任何上下文。

作为一个不同的示例:

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

Fizz 函数被设计为构造函数,以便在运行时将 buzz 函数分配给新创建的对象。也就是说,您可以像这样使用它:

const obj = new Fizz();
obj.buzz();

或更简洁(如果您在调用 buzz 后不需要保留对象):

new Fizz().buzz();

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

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

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

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

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

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

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object. That is, you'd use it like this:

const obj = new Fizz();
obj.buzz();

or more concisely (if you don't need to keep the object after calling buzz):

new Fizz().buzz();
故事和酒 2024-12-09 19:53:06

这称为闭包

基本上,在其他函数中定义的函数只能在该函数中访问。但可以作为结果传递,然后可以调用该结果。

这是一个非常强大的功能。您可以在此处查看更多说明:

javascript_closures_for_dummies.html 镜像在 Archive.org 上

It is called closure.

Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.

It is a very powerful feature. You can see more explanation here:

javascript_closures_for_dummies.html mirror on Archive.org

谁对谁错谁最难过 2024-12-09 19:53:06
function x() {}

相当于(或非常相似),

var x = function() {}

除非我弄错了。

所以没有什么有趣的事情发生。

function x() {}

is equivalent (or very similar) to

var x = function() {}

unless I'm mistaken.

So there is nothing funny going on.

生生漫 2024-12-09 19:53:06

函数内部和外部都允许进行函数实例化。在这些函数内部,就像变量一样,嵌套函数是局部的,因此无法从外部作用域获取。

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

foo 在其自身内部操作barbar 不能从外部作用域触及,除非它是在外部作用域中定义的。

所以这行不通:

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

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

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
许久 2024-12-09 19:53:06

当您在函数中声明函数时,内部函数仅在声明它们的范围内可用,或者在您的情况下,pad2只能在dmy中调用代码>范围。

dmy 中存在的所有变量在 pad2 中都可见,但反之则不会发生 :D

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

尸血腥色 2024-12-09 19:53:06

在 JavaScript(以及许多语言)中,函数内包含函数是完全正常的。

花时间学习该语言,不要因为它与您已经知道的内容相似而使用它。我建议观看 Douglas Crockford 关于 JavaScript 的 YUI 演示系列,特别关注 第三幕:发挥终极功能(链接到视频下载、幻灯片和文字记录)

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)

依 靠 2024-12-09 19:53:06
function foo() {
  function bar() {
    return 1;
  }
}
bar();

Will throw an error.
Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

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

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

Will throw an error.
Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

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

风柔一江水 2024-12-09 19:53:06

嵌套函数可以作为编写相关函数的模块化组的基础,有点像完全面向对象编程(仅限静态类)。

下面是这样一组函数的示例,在本例中将值转换为 JSON 字符串或将 JSON 字符串转换为值。

请注意内部函数如何分组为外部函数内的对象,以及如何将对象存储到组名称中。这是从组外直接可见的唯一名称。要从外部访问任何包含的函数,只需写入组名称、句点,然后是函数名称。要从内部访问包含的函数,您可以使用相同的符号,或“this”,一个句点,然后是函数名称。

//--------------------------------------------------------------------//
//      Module J:
//          Convert from and to JSON strings
//--------------------------------------------------------------------//
const J=NewJ();
function NewJ()
    {
    const mod=
        {
        From:(str)=>
            {
            return JSON.parse(str);
            }, // From
        To:(val)=>
            {
            return JSON.stringify(val,null,3);
            } // To
        }; // mod
    return mod;
    } // NewJ

//--------------------------------------------------------------------//
//      End Module J
//--------------------------------------------------------------------//

这是一个测试:

console.log(J.To({A:'a'}));

控制台输出:

{
   "A": "a"
}

Nested functions can be the basis for writing a modular group of related functions, kind of halfway to full object-oriented programming (static classes only).

Here is an example of such a group of functions, in this case to convert a value to a JSON string or a JSON string to a value.

Notice how the inner functions are grouped into an Object inside an outer function, and how the Object is then stored into a group name. This is the only name directly visible from outside the group. To reach any contained function from outside, you just write the group name, a period, then the function name. To reach a contained function from inside, you can use the same notation, or 'this', a period, then the function name.

//--------------------------------------------------------------------//
//      Module J:
//          Convert from and to JSON strings
//--------------------------------------------------------------------//
const J=NewJ();
function NewJ()
    {
    const mod=
        {
        From:(str)=>
            {
            return JSON.parse(str);
            }, // From
        To:(val)=>
            {
            return JSON.stringify(val,null,3);
            } // To
        }; // mod
    return mod;
    } // NewJ

//--------------------------------------------------------------------//
//      End Module J
//--------------------------------------------------------------------//

Here's a test:

console.log(J.To({A:'a'}));

Console output:

{
   "A": "a"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文