[英]JavaScript - how to identify or define THE “global” (super-global) for cross-platform use in strict mode
I'm looking for a way to check if the "global" (super-global, -like "window") exists -and if not, to create it as such. 我正在寻找一种方法来检查“全局”(超级全局,类似“窗口”)是否存在 - 如果不存在,则创建它。
I've seen this done in some code on GitHub a few weeks ago, but, now that I need it, I can't find it anywhere. 我几周前在GitHub上的一些代码中看到过这个,但是,现在我需要它,我无法在任何地方找到它。 I may have miss-looked, but it was very short and all intelligent like on 1 (short) line - without
if
, and without using var
(or let
) - in global scope --> in strict mode. 我可能看上去很简陋,但它非常简短并且在1(短)线上都是智能的 -
if
没有使用var
(或let
) - 在全局范围内 - >在严格模式下。
I've been searching for 2 hours trying to find this and all I can find is countless references to "global variables" - which in this case, clearly not a "variable" as the super-global "window" (or in NodeJS "global") is not mutable. 我一直在寻找2小时试图找到这个,我所能找到的是对“全局变量”的无数引用 - 在这种情况下,显然不是“变量”作为超全局“窗口”(或在NodeJS中)全局“)不可变。
The solution I currently have is not that great, but it works, sort-of: 我目前拥有的解决方案并不是那么好,但它的工作原理是:
"use strict";
if ('undefined' == typeof global)
{
Object.defineProperty
(
window,'global',
{
writable:false,
configurable:false,
enumerable:false,
value:window
}
);
}
So, if you try something like: 所以,如果你尝试类似的东西:
global = 'bite me!';
Then the behavior is as expected, it throws: 然后行为是预期的,它抛出:
Uncaught TypeError: Cannot assign to read only property 'global' of...
未捕获的TypeError:无法分配给只读属性'global'...
Which is good, -exactly as it should behave. 哪个好,就像它应该表现的那样。
I'm not sure if this is the correct way to define it, because if I do something like: 我不确定这是否是正确的定义方式,因为如果我这样做:
console.log(global);
Then the console shows something like this: 然后控制台显示如下内容:
Window {top: Window, ...
窗口{顶部:窗口,......
Which tells me that it is not identified as "global" but as "window"; 这告诉我它不是“全球”而是“窗口”; -which is all fair and well being a "circular";
- 这是公平的,也是一个“循环”; however, I'm sure there's a better way to do this.
但是,我确信有更好的方法可以做到这一点。
Any input will be much appreciated, thanks 任何意见都将非常感谢,谢谢
I never thought this would actually work; 我从未想过这会真正起作用; but it does!
但确实如此!
In global scope, after use strict;
在全球范围内,
use strict;
后use strict;
you can simply do this: 你可以这样做:
this.Main = this;
Now you can simply call and define things on Main
as you would with window
-or- global
; 现在,您可以像使用
window
-or- global
一样简单地调用和定义Main
; and these new properties will exist in the global scope as expected. 并且这些新属性将按预期存在于全局范围内。
After you've made the changes you want to this object; 在您对此对象进行更改之后; simply call:
只需致电:
Object.freeze(this.Main); // makes it immutable
If you want to do it all in one go (for no valid reason whatsoever) you can do this: 如果你想一次性完成(没有任何正当理由),你可以这样做:
Object.freeze(this.Main=this); // it actually works!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.