Home  >  Article  >  Web Front-end  >  Detailed introduction to the closure problem (2)

Detailed introduction to the closure problem (2)

零下一度
零下一度Original
2017-06-26 10:53:321081browse
<span style="font-size: 15px"><code>我在整理闭包问题的时候,看到一道前端面试题<br>for (var i = 0; i < 10; i++) {
  setTimeout(function() {
    console.log(i);
    }, 0);
}<br>了解 js 的异步机制的都知道,输出结果是: <code>10 10 10 ... 10<br></code>然后面试官又问  如果希望得到的是<code>0 1 2 ... 9</code>,如何能够解决这个问题<br><br>我脑海想到的第一个解决方法就是用let代替var使for形成块级作用域;<br><br>第二个解决方法,使setTimeout函数立即执行,形成同步输出:<br></code></span>
<span style="font-size: 15px"><code>for (var i=0; i < 10; i++) {
  (function (temp) {
    setTimeout(function() {
      console.log(temp);
    }, 0);
  })(i);
}<br><br>如果有其他解决方法,亲爱的朋友们可以评论补充<br><br>再补充一道闭包问题:<br></code></span>
function fun(n,o){
  console.log(o);
  return {
    fun:function(m){
      return fun(m,n);
    }
  }
}

var a=fun(0);
a.fun(1);
a.fun(2);
a.fun(3);
var b=fun(0).fun(1).fun(2).fun(3);
var c=fun(0).fun(1);
c.fun(2);
c.fun(3);
<span style="font-size: 15px"><code>这道题可以较深理解闭包机制,解决这道题比较重要的是理解被保护的数据是哪一个,运行的顺序之类的,输出:<br></code></span>
var a=_fun_(0);//undefined
a.fun(1);//0
a.fun(2);//0
a.fun(3);//0

var b=_fun_(0).fun(1).fun(2).fun(3);
//undefined,0,1,2

var c=fun(0).fun(1);//undefined,0,
c.fun(2);//1
c.fun(3); //1
<span style="font-size: 15px"><code>我在这就不多做解释了,想一下很容易通的<br><br><br></code></span>
 <br>

The above is the detailed content of Detailed introduction to the closure problem (2). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn