取自 nanoajax ( https://github.com/yanatan16/nanoajax )。为什么不直接传入this,返回this的自执行函数有什么用?
!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 }());
最佳答案
它确保参数确实是全局对象(在浏览器中为 window
或在 node/iojs 中为 root
),如果 this
则可能不同在外部范围内不是。
示例:
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();
在这里,路过this
不会传递全局对象。
请注意,此代码是自动缩小操作的产物。
关于javascript - 'function(){ return this }()' 作为参数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218342/