hguser
hguser

Reputation: 36028

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;
}

Upvotes: 3

Views: 187

Answers (3)

user1823761
user1823761

Reputation:

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.

Upvotes: 3

Blender
Blender

Reputation: 298166

The first one creates an anonymous function that just returns the location of the current script. The location is computed only once and is a static string that's returned by the function.

The second one recalculates the location each time you call it. While they produce the same results, the second one will be much slower than the first, which is really just a return statement.

Upvotes: 1

recneps
recneps

Reputation: 1295

Because of scope, by doing this you do not create another function that will remain in global scope. If you created a function with a name it will remain as a object in globa scope, plus you would need to call it. There is a good read here. http://helephant.com/2008/08/23/javascript-anonymous-functions/.

Upvotes: 0

Related Questions