mirror of
https://github.com/fofolee/uTools-Manuals.git
synced 2025-12-17 08:26:32 +08:00
语法高亮,滚动条美化,设置页面调整
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
</div><p></p>
|
||||
<p><code>globalThis</code> 可以获取全局对象。</p>
|
||||
<h2 id="语法">语法</h2>
|
||||
<pre class="syntaxbox">globalThis</pre>
|
||||
<pre><code class="language-javascript">globalThis</code></pre>
|
||||
<h2 id="描述">描述</h2>
|
||||
<p>事实上,在不同的 JavaScript 环境中拿到全局对象是需要不同的语句的。在 Web 中,可以通过 <code>window</code>、<code>self</code> 或者 <code>frames</code> 取到全局对象,但是在 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Web Workers</a> 中只有 <code>self</code> 可以。在 Node.js 中,它们都无法获取,必须使用 <code>global</code>。在松散模式下,可以在函数中返回 <code>this</code> 来获取全局对象,但是在严格模式下 <code>this</code> 会返回 <code>undefined</code> 。</p>
|
||||
<p><code>globalThis</code> 提供了一个标准的方式去获取不同环境下的全局对象。它不像 <code>window</code> 或者 <code>self</code> 这些属性,而是确保可以在有无窗口的环境下都可以正常工作。所以你可以安心的使用 <code>globalThis</code> ,不必担心它的运行环境。</p>
|
||||
@@ -13,7 +13,7 @@
|
||||
<p>此特性曾经在提案时命名为 <code>global</code>,但有些网站会因此运行不正常,所以改名为 <code>globalThis</code> 了。</p>
|
||||
<h2 id="示例">示例</h2>
|
||||
<p>在 <code>globalThis</code> 之前,获取某个全局对象的唯一方式就是 <code>Function('return this')()</code>,但是这在某些情况下会导致 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">CSP</a> 危害,所以 <a class="external" href="https://github.com/paulmillr/es6-shim" rel="noopener">es6-shim</a> 使用如下的方式:</p>
|
||||
<pre class="brush: js"><code>var getGlobal = function () {
|
||||
<pre><code class="language-javascript"><code>var getGlobal = function () {
|
||||
if (typeof self !== 'undefined') { return self; }
|
||||
if (typeof window !== 'undefined') { return window; }
|
||||
if (typeof global !== 'undefined') { return global; }
|
||||
@@ -24,12 +24,12 @@ var globals = getGlobal();
|
||||
|
||||
if (typeof globals.setTimeout !== 'function') {
|
||||
// no setTimeout in this environment!
|
||||
}</code></pre>
|
||||
}</code></code></pre>
|
||||
<p>但是有了 <code>globalThis</code> 之后,只需要:</p>
|
||||
<pre class="brush: js"><code>if (typeof globalThis.setTimeout !== 'function') {
|
||||
<pre><code class="language-javascript"><code>if (typeof globalThis.setTimeout !== 'function') {
|
||||
// no setTimeout in this environment!
|
||||
}</code>
|
||||
</pre>
|
||||
</code></pre>
|
||||
<h2 id="规范">规范</h2>
|
||||
<table class="standard-table">
|
||||
<tbody>
|
||||
|
||||
Reference in New Issue
Block a user