Functions are another type of variable in JavaScript (with some nuances, of course). Creating a function inside another function changes the scope in the same way as changing the scope of a variable. This is especially important for use with closure to reduce overall global namespace pollution.
Functions defined in another function will not be accessible outside the function unless they are bound to an object 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 executing the foo function, since it is overridden by window.baz . The bar function will not be available in any context other than the areas contained in the foo function.
as another example:
function Fizz(qux) { this.buzz = function(){ console.log( qux ); }; }
The Fizz function is intended as a constructor, so when it starts, it assigns the buzz function to the newly created object.
zzzzBov Sep 03 2018-11-11T00: 00Z
source share