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
This question is related to
javascript
nested-function
function foo() {_x000D_
function bar() {_x000D_
return 1;_x000D_
}_x000D_
}_x000D_
bar();
_x000D_
bar
is defined inside foo
, bar
will only be accessible inside foo
.bar
you need to run it inside foo
. function foo() {_x000D_
function bar() {_x000D_
return 1;_x000D_
}_x000D_
bar();_x000D_
}
_x000D_
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)
function x() {}
is equivalent (or very similar) to
var x = function() {}
unless I'm mistaken.
So there is nothing funny going on.
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 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:
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
Source: Stackoverflow.com