Search code examples
javascriptbrowseriife

Self invoking functions javascript


I wrote a self invoking function in both firefox and chrome it it wouldn't invoke.

I wrote something to the effect of

(function () { alert("THE"); })();

do self invoking functions not work in current browsers?

I did include all essential tags and all other code works on the page


Solution

  • "Self-invoking functions" are not really a part of javascript, it's just a term that people are calling a specific pattern of code (like AJAX, etc.); these patterns should work anywhere that javascript works.

    What you're calling a "self-invoking function" is just creating an anonymous function and immediately calling it (as opposed to say storing it in a var, as an object value, as a function param, etc.).

    That is, the following are basically the same:

    var f = function(){...}; f()
    

    and

    ( function(){...} )()
    

    So because your 'self-invoking function' is a basic part of javascript, there is no possible way it's not working unless the insides aren't working or your environment is messed up. You could copy-paste your code onto a new blank page, and it would work fine. Something else must be going wrong:

    Check your errors in your dev console. Specifically, check to make sure you don't have a syntax error or that there isn't some weird thing going on with the webpage you're testing it on (e.g. if you somehow redefine alert...).