user3267755 user3267755 - 4 months ago 16
Javascript Question

Function scope in anonymous functions

I've just configured gulp / bower to minify & bundle my javascript files and I've created a handful of individual JS files that follow the format of a self-executing anonymous function. e.g. let's say I have a file called "mobile-functions.js" which contains a function called "isViewportInMobile".

mobile-functions.js

(function ($) {

function isViewportInMobile(mobileWidthOverride) {
var widthToCheckAgainst = mobileWidthOverride || 768;
return window.innerWidth < widthToCheckAgainst;
}

})(jQuery);


How do I call that function from a different Javascript file (that also follows the self-executing anonymous function format)? When I'm trying to use the function in my other file, it says that isViewportInMobile is undefined.

Answer

Depending on how much access you have to the file in question, you could modify it slightly to pass the scope of the self invoking function to a variable. However, I'd assume that if you had such access you probably wouldn't need to create this thread, but none the less here's how you can do it...

var something = (function($) {

    this.isViewportInMobile(mobileWidthOverride) {
        var widthToCheckAgainst = mobileWidthOverride || 768;
        return window.innerWidth < widthToCheckAgainst;
    };

    return this;
})(jQuery);

This would then allow you to call the function like this:

something.isViewportInMobile(params);

I hope this was of some use.

Comments