I'm working on a function that is too complicated (processor) so I embedded part of the functionality in a nested "utility function" inside it (print). A simplified version of it looks like this:
var out = document.getElementById( "output" );
function processor ( n ) {
function print( msg ) {
out.innerHTML += msg;
}
while ( n > 0 ) {
print( n-- );
print( ", " );
}
print( "<br/>" );
}
for ( var i = 0; i < 10; i++ ) {
processor( i );
}
You can see it in action in this JSfiddle.
The question is: am I really creating 10 instances of the utility function print()
? If yes, what is a more efficient way to write this code without putting the utility function outside the processor()
function? I want the print()
function to only be accessible in processor()
and nowhere else. One solution is namespace.
I've read this question and even though it's related but it's not directly my answer: Efficiency of creating an event handler in a nested loop: am I creating 1440 functions here?