Home > Web Front-end > JS Tutorial > body text

Share an interview question about closures, bind and this

高洛峰
Release: 2017-02-21 14:50:15
Original
985 people have browsed it

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>
Copy after login

# #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();
Copy after login

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();
Copy after login

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();
Copy after login

For more articles related to sharing an interview question about closure, bind and this, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!