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

Share an interview question about closures, bind and this

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

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

  • 这是第一个li
  • 这是第二个li
  • 这是第三个li

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

var init = function(){
var obj = document.getElementById('text');
for(var i=0;i

Answer 2: Closure

var init = function(){
var lis=document.querySelectorAll("#text li");
 for(var i=0;i

Solution 3:The stupidest method, matching

var init = function(){
 var obj = document.getElementById('text');
 for(var i=0;i

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