1

Besides readability, is there any reason to avoid or not program static variables using this style?

function not_global()
{
    var print;

    (function() {
        var static = value;
        print = function(value) {
            static = value;
        }
    })();
}
6
  • that's global, which means you're polluting the global namespace. Commented Jan 31, 2014 at 0:17
  • Given that you're declaring the variable in the global namespace, this just seems unnecessarily convoluted. Commented Jan 31, 2014 at 0:17
  • function foo(){}; foo.bar = function(){}; bar here would be a "static" property/variable as it is only accessible by foo.bar Commented Jan 31, 2014 at 0:19
  • 2
    sorry, its within another function Commented Jan 31, 2014 at 0:20
  • It's not static - but a normal variable, or a free variable from the IIFE perspective Commented Jan 31, 2014 at 0:20

1 Answer 1

1

I would avoid that style. It isn't very explicit so it becomes difficult without comments to tell that print being exposed outside of the IIFE is intentional. Instead, I would suggest returning print from the function and assigning it there:

var print = (function()
{
    var text_log=document.getElementById('text_log_text');

    return function(string)
    {
        text_log.innerHTML+='<br />'+string;
    };
})();

Note that polluting the global namespace is discouraged, so really the best answer here is to just not have print exposed outside. This answer assumes you have already thought through that, and either your IIFE is actually nested in another function (so it isn't polluting the global namespace), or you really do want print to be global.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.