Home >Web Front-end >JS Tutorial >Share an interview question about closures, bind and this

Share an interview question about closures, bind and this

高洛峰
高洛峰Original
2017-02-21 14:50:151037browse

This article mainly introduces you to an interview question about closure bind and this. The article gives detailed sample code. Friends in need can refer to it. Let’s take a look together.

The problem to be solved is to add a click event for each li for the following ul, and pop up the corresponding index

<ul id="text">
 <li>这是第一个li</li>
 <li>这是第二个li</li>
 <li>这是第三个li</li>
</ul>

# #Answer 1: bind, point the current anonymous function to this, and pass i as the parameter

var init = function(){
var obj = document.getElementById(&#39;text&#39;);
for(var i=0;i<obj.children.length;i++){
 obj.children[i].addEventListener(&#39;click&#39;,function(i){
 alert(i)
 }.bind(this,i))
}
}
init();

Answer 2: Closure

var init = function(){
var lis=document.querySelectorAll("#text li");
 for(var i=0;i<lis.length;i++){
 lis[i].onclick=(function(i){
  return function(){
   alert(i);
  };
 })(i)
 }
}
init();

Solution 3:The stupidest method, matching

var init = function(){
 var obj = document.getElementById(&#39;text&#39;);
 for(var i=0;i<obj.children.length;i++){
 obj.children[i].addEventListener(&#39;click&#39;,function(item){
 var self = item.target;
 for(var j=0;j<obj.children.length;j++){
 if(self == obj.children[j]){
  alert(j);
 }
 }
 })
 }
}
init();

For more articles related to sharing an interview question about closure, bind and this, please pay attention to 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