Heim >Backend-Entwicklung >Python-Tutorial >JavaScript 如何获取闭包变量?
<span class="kd">var</span> <span class="nx">o</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="p">{</span> <span class="c1">// let person 竟然也会被外部拿到 let 被打脸了啊</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">'Vincent'</span><span class="p">,</span> <span class="nx">age</span><span class="o">:</span> <span class="mi">24</span><span class="p">,</span> <span class="nx">__proto__</span> <span class="o">:</span> <span class="kc">null</span> <span class="c1">// 是的你没有 看错 真的是 指向 null</span> <span class="p">};</span> <span class="k">return</span> <span class="p">{</span> <span class="nx">run</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">k</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">person</span><span class="p">[</span><span class="nx">k</span><span class="p">];</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}());</span> <span class="c1">// 那么问题来了, 挖掘机技术 呸呸呸 说错了 口误! </span>
<code class="language-js"><span class="kd">var</span> <span class="nx">o</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="kd">var</span> <span class="nx">b</span> <span class="o">=</span> <span class="mi">42</span>
<span class="k">return</span> <span class="p">{</span>
<span class="nx">foo</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span><span class="p">)</span>
<span class="k">return</span> <span class="nx">b</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">})()</span>
</code>
我也来抖个机灵:IE9 下 __proto__ 是无效的呢。所以在 Object.prototype 上添加 getter 的方法在 IE9 下依然有效。
如果你引擎实现得好的话,那么——是做不到的。你可以试着用霍尔逻辑证明一下……