Execute javscript when theme customizer loads (autosave issue)

In the JavaScript CODE below:

( function( wp, $ ) {

    function bob() {
        alert('bob');
    }
    // Etc
} )( wp, jQuery );

bob function is scoped only within this block:

( function( wp, $ ) {
    // functions defined here are not accessible from outside
} )( wp, jQuery );

That’s why when you load the inline script and call bob(), you get bob is undefined error.

You’ll get the same error, if you do this:

( function( wp, $ ) {

    function bob() {
        alert('bob');
    }
    // Etc
} )( wp, jQuery );
// bob is undefined here.
bob();

This code structure is known as Immediately-Invoked Function Expression (IIFE).

You can avoid this error by doing something like this:

( function( wp, $, w ) {

    w.bob = function() {
        alert('bob');
    }
    // other code not part of the window object
} )( wp, jQuery, window );
// bob is now defined here.
bob();

But remember, now that you are using the window object, it can now have naming conflict with other variables defined in the global scope. So the function names must be unique.