访问全局对象 [英] Accessing the global object
问题描述
无论如何都要从其他函数内部访问全局对象,而不是执行var _global = this;;在声明功能之前?
谢谢
Is there anyway to access the global object from inside a function other
than doing a "var _global = this;" before declaring the function?
Thanks
推荐答案
" Bob" < no **** @ nowhere.comwrites:
"Bob" <no****@nowhere.comwrites:
无论如何从一个函数内部访问全局对象
比做一个var _global = this;在声明功能之前?
Is there anyway to access the global object from inside a function other
than doing a "var _global = this;" before declaring the function?
如果你知道全局的名字而且你确定你没有覆盖
的名字,你可以使用全球名称。
IWO,是和否。
-
Joost Diepenmaat |博客: http://joost.zeekat.nl/ |工作: http://zeekat.nl/
If you know the name of the global and you''re sure you''re not overriding
the name, you can use the global name.
IWO, yes and no.
--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
>
2月21日下午5:10,Bob < nob ... @ nowhere.comwrote:
On Feb 21, 5:10 pm, "Bob" <nob...@nowhere.comwrote:
无论如何从一个函数内部访问全局对象
比做avar _global = this;在声明功能之前?
Is there anyway to access the global object from inside a function other
than doing a "var _global = this;" before declaring the function?
在网络浏览器中,全局对象通常作为属性提供
" window"全球对象。我认为你创建自己的想法
" _global"更好。在ECMAScript 4中,将引用全局对象的默认全局
属性。它会像窗口一样工作。但是窗口在
非浏览器主机中编写脚本时,这是一个坏名字。
Peter
In a web browser the global object is usually available as a property
"window" of the global object. I think your idea of creating your own
"_global" is better. In ECMAScript 4 there will be a default "global"
property of the global object that references the global object. It
will work like "window" but "window" is a bad name when scripting in a
non-browser host.
Peter
Bob写道:
Bob wrote:
无论如何都要从
函数内部访问全局对象,而不是执行var _global = this; ;
之前声明这个功能?
Is there anyway to access the global object from inside a
function other than doing a "var _global = this;" before
declaring the function?
在javascript中, - this - 关键字的值取决于如何调用
函数。如果该函数未被调用为对象的方法
,则 - this - 关键字的值默认为对全局
对象的引用。因此,在任何情况下,您都可以使用以下方式获取对全局
对象的引用:
函数x(){
...
var localGlobalRef = function(){return this;}();
...
}
这在ECMAScript 3rd Ed中是100%可靠的。实现,并且非常有用,但看起来ES 4在这个
方面不会与ES 3重新兼容。尽管如此,没有与ES 3背部兼容可能(手指交叉)足以杀死摇篮中的ES 4,所以也许这不值得担心。
Richard。
In javascript the value of the - this - keyword is determined by how a
function is called. If the function is not called as a method of an object
the value of the - this - keyword defaults to a reference to the global
object. As a result, from any context you can get a reference to the global
object using:-
function x(){
...
var localGlobalRef = function(){return this;}();
...
}
This is 100% reliable in ECMAScript 3rd Ed. implementations, and quite
useful, but it looks like ES 4 will not be back-compatible with ES 3 in this
regard. Still, not being back-compatible with ES 3 may (fingers crossed) be
enough to kill ES 4 in its cradle so maybe that is not worth worrying about.
Richard.
这篇关于访问全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!