0
votes

Is there a risk in declaring and calling a function without assigning it to a var ?

Normaly, I put my javascript this way:

 $(document).ready(function (ev) {

        var myFunc =  function () { 
            init();
    
            function init() {
                initEvents();
            };
    
            function initEvents() {
                ...
            };
    
        }();

But since the var is never used, and could conflict with another one in the global namespace, I am thinking of doing this instead:

  $(document).ready(function (ev) {

        new function () { 
            init();
    
            function init() {
                initEvents();
            };
    
            function initEvents() {
                ...
            };
    
        }();

Seems to work, but any danger ?

Based on the comments received, I think the solution would be to do this instead:

$(document).ready(function (ev) {
    
                init();
        
                function init() {
                    initEvents();
                };
        
                function initEvents() {
                    ...
                };
});
   
The var declared inside your "ready" handler won't cause problems with global variables; as you said, it isn't used anyway. Also, new function() is just as pointless as assigning to a variable you never use.Pointy
Anonymous functions are fine, don't need the new keyword. Although it looks like the function won't get called?NickSlash
Self-Invoking Anonymous Function probably it what you need.Martinez
The argument to ready is a function, which is what you're giving it; essentially every example of jQuery's ready is exactly this. It's unclear what the issue is/was.Dave Newton
IIFE (Immediately Invoked Function Expression) (aka self-invoking anonymous function as named above) is useful if you want to wrap a variable, eg (function($) { $(...); })(jQuery); where $ is not defined as jquery outside the IIFE (eg via noconflict). There's no point in having one as in your second example as it just runs the code that it would if it wasn't there (like your 3 "solution")freedomn-m