【发布时间】:2015-03-07 16:41:06
【问题描述】:
抱歉,我想不出更好的问题标题。
我的问题是,在 he.js 中,根据 https://github.com/mathiasbynens/he/blob/master/he.js ,他们正在使用以下代码:
/*! https://mths.be/he v0.5.0 by @mathias | MIT license */
;(function(root) {
//...omitted
var he = {
'version': '0.5.0',
'encode': encode,
'decode': decode,
'escape': escape,
'unescape': decode
};
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define(function() {
return he;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = he;
} else { // in Narwhal or RingoJS v0.7.0-
for (var key in he) {
has(he, key) && (freeExports[key] = he[key]);
}
}
} else { // in Rhino or a web browser
root.he = he;
}
}(this));
如果你把它导入到你的页面中
<script src="he.js"></script>
您可以将页面中的方法称为he.encode(...)。
我的问题是,它究竟是如何设置变量he的?
我的意思是,我可以看到
} else { // in Rhino or a web browser
root.he = he;
}
}(this));
但是在}(this)); 的调用下,this 到底是什么?
【问题讨论】:
-
this将是window, - 执行函数时的this实例,即window -
@RaraituL 哦,我明白了!谢谢你。我以为可能是
document什么的,没想到window。再次感谢! -
he.js 加载时,它定义了一个匿名函数(文件中顶级 {} 之间的所有内容)。然后它通过传递窗口对象调用该函数。它是通过执行'(this));'来完成的
标签: javascript module global