Ryan Detzel
Ryan Detzel

Reputation: 5599

What does 'function(){ return this }()' do as an argument?

Taken from nanoajax (https://github.com/yanatan16/nanoajax). Why not just pass in this, what does the self execution function returning this do?

!function(e, t) {
    function n() {
        if (t.XMLHttpRequest) return new t.XMLHttpRequest;
        try {
            return new t.ActiveXObject("MSXML2.XMLHTTP.3.0")
        } catch (e) {}
    }
    t.nanoajax = e, e.ajax = function(e, t, r) {
        r || (r = t, t = null);
        var u = n();
        return u ? (u.onreadystatechange = function() {
            4 == u.readyState && r(u.status, u.responseText)
        }, t ? (u.open("POST", e, !0), u.setRequestHeader("X-Requested-With", "XMLHttpRequest"), u.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")) : u.open("GET", e, !0), void u.send(t)) : r(new Error("no request"))
    }
}({}, function() { return this }());

Upvotes: 4

Views: 107

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382274

It ensures the argument is really the global object (window in a browser or root on node/iojs), which could be different if this in the external scope weren't.

Example :

function A(){
}
A.prototype.doIt = function(){
  !function(a){
    console.log(a);
  }(function() { return this }()); // passing this would pass the instance of A
};
(new A).doIt();

Here, passing this would not pass the global object.

Note that this code is the product of an automated minification operation.

Upvotes: 3

Related Questions