Define js function inside another js function
I recently found this piece of code:
function start() {
function sleep(milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
sleep(10000);
return "Hello Start";
}
What advantages do we have for defining functions in this way instead of using the "traditional" approach?
Thanks in advance.
source to share
The advantage of this is that your function is sleep
no longer defined in the global scope. It is limited by function start
.
This is beneficial because putting all of your functions in the global scope can cause conflicts with other scripts.
There's nothing traditional
about defining all functions as global, it's just bad practice that has been perpetuated. Fingerprint shrinking global
is a good and responsible practice that will reduce conflicts between your scripts and other scripts that may be included in your applications.
source to share
It is related to the area. Consider putting together a copy of the recently published Secrets of JavaScript Ninja for a great overview of JavaScript. But we can use your browser console to try this (may not work in Internet Explorer, use Chrome):
> function start() { function bob() { console.log('bob'); } bob() };
> start()
> bob
> bob()
> ReferenceError: bob is not defined
So you can see that the function bob
inside is start
not included in the scope outside the function start
. There are several reasons for this.
source to share