Search code examples
javascriptself-executing-function

Why use the self executing anonymous function when get the script path


I found people use this method to get the path of the current script location:

    _getScriptLocation: (function() {
        var r = new RegExp("(^|(.*?\\/))(" + scriptName + ")(\\?|$)"),
            s = document.getElementsByTagName('script'),
            src, m, l = "";
        for(var i=0, len=s.length; i<len; i++) {
            src = s[i].getAttribute('src');
            if(src) {
                m = src.match(r);
                if(m) {
                    l = m[1];
                    break;
                }
            }
        }
        return (function() { return l; });
    })(),

Full codes here.

But I do not know why it use the self executing anonymous function?

Why not use this instead:

_getScriptLocation: function() {
    var r = new RegExp("(^|(.*?\\/))(" + scriptName + ")(\\?|$)"),
        s = document.getElementsByTagName('script'),
        src, m, l = "";
    for(var i=0, len=s.length; i<len; i++) {
        src = s[i].getAttribute('src');
        if(src) {
            m = src.match(r);
            if(m) {
                l = m[1];
                break;
            }
        }
    }
    return l;
}

Solution

  • In the first one (self executing function), the process of function execute just once, so:

    APP._getScriptLocation();
    APP._getScriptLocation();
    APP._getScriptLocation();
    

    is just returning the l for each call (the process will never execute again - it's just execute once your script loaded: because it was a self executing function).

    But in the second one, whenever you call your method:

    APP._getScriptLocation();
    

    You are executing all the process again and again which is not needed in this case.