Maison >développement back-end >Tutoriel Python >到底什么是闭包?
<code class="language-js"><span class="kd">let</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="kd">let</span> <span class="nx">b</span> <span class="o">=</span> <span class="kd">function</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="p">)</span>
<span class="p">}</span>
</code>
最近特别注意的看了一些关于闭包的东西,比方说这个Closures are functions that refer to independent (free) variables. In
other words, the function defined in the closure 'remembers' the
environment in which it was created.
Closures - JavaScript
A closure is a special kind of object that combines two things: a
function, and the environment in which that function was created. The
environment consists of any local variables that were in-scope at the
time that the closure was created.
<code class="language-text">var inc = (function () { // 该函数体中的语句将被立即执行
var count = 0; // 局部变量初始化
return function () { // 返回一个内嵌的闭包函数引用
return ++count; // 当外部函数 return 后,这里的 count 不再是外部函数的局部变量。
};
}) ();
inc(); // count: 1
inc(); // count: 2
</code>
其他答案的解释都已经很详细了,我就不多写自己的理解了,但貌似都只有文字描述或许不方便新人理解,我就show我滴渣渣code吧,写四个例子啦,如果看明白了就大概懂了~<code class="language-text">function love(name) {
var text = 'Hello ' + name;
var me = function() {
console.log(text);
}
return me;
}
var loveme = love('AutumnsWind');
loveme(); // 输出 Hello AutumnsWind
</code>
首先,闭包是一个函数,而且是一个有权访问另一个函数作用域中的变量的函数。<code class="language-js"><span class="kd">function</span> <span class="nx">f</span><span class="p">(</span><span class="nx">a</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">a</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code>
一点浅见<code class="language-js"><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span><span class="o">=</span><span class="mi">1</span><span class="p">;</span> <span class="nx">i</span><span class="o"><span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">setTimeout</span><span class="p">(</span> <span class="kd">function</span> <span class="nx">timer</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">i</span> <span class="p">);</span>
<span class="p">},</span> <span class="nx">i</span><span class="o">*</span><span class="mi">1000</span> <span class="p">);</span>
<span class="p">}</span>
</span></code>
相继式(Sequent)中的前件(Antesedent)。
不会js,就说闭包这个概念。