JavaScript嵌套函数 [英] JavaScript Nested function

查看:151
本文介绍了JavaScript嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段javascript的代码我不明白:

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

如何在另一个函数中定义函数?我们可以从my()函数外部调用pad2()吗?

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

请注意一下。谢谢

推荐答案

函数是JavaScript中的另一种变量(当然还有一些细微差别)。在另一个函数中创建函数会改变函数的范围,就像更改变量范围一样。这对于使用闭包来减少总体命名空间污染尤为重要。

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

在这个例子中,baz函数可以在<$之后使用c $ c> foo 函数已经运行,因为它已被覆盖 window.baz 。除了 foo 函数中包含的范围之外,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.

作为不同的例如:

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

Fizz 功能被设计为构造函数,以便在运行时为新创建的对象分配 buzz 函数。

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object.

这篇关于JavaScript嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆