Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to make sense of "this" in my javascript code (one thing works, the other doesn't)

I've been trying to learn javascript by refactoring some Jquery examples in a book into javascript. In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab.

var tabs = document.querySelectorAll(".tabs a span");
var content = document.querySelectorAll("main .content li");

for (var tabNumber = 0; tabNumber <= 2; tabNumber++) {
  tabs[tabNumber].addEventListener("click", function (event) {
    
    for (var i = 0; i < tabs.length; i++) {
      tabs[i].classList.remove("active");
    }
    tabs[tabNumber].classList.add("active");
    for (var i = 0; i < content.length; i++) {
      content[i].innerHTML = "";
    }
    event.preventDefault();
  });
}

This returns an undefined error when I run it. However, I tried replacing tabs[tabNumber].classList.add("active") with this.classList.add("active") and it worked.

Why doesn't the previous code work? As far as I can see they are referring to the same thing, and tabs[tabNumber] should work since at that point in the code it is tabs[0].

like image 716
HsinWang5 Avatar asked Mar 14 '16 01:03

HsinWang5


People also ask

Why is JavaScript this so confusing?

JavaScript is so hard to learn because it's an asynchronous programming language. It's also single-threaded, which means it uses its asynchronous nature in a radically different way than most other programming languages.

Why does my JavaScript not work?

On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.

When there is a problem with JavaScript code there are generally two types of errors?

Namely, with JavaScript, most of our errors fit into two categories: syntax errors and runtime errors. A syntax error is a problem with the grammar in our code. Syntax errors mostly come in the form of misspelled keywords, missing or open brackets, or missing parentheses or punctuation.


1 Answers

If use this, I think it's better and a more polished solution. If you still want to use tabNumber, it's probably evaluating to 3 in every click callback, because it's the number after the last iteration, and you don't have a tabs[3] position.

So, you just have to make a closure of the tabNumber variable.

like image 74
Niloct Avatar answered Sep 28 '22 00:09

Niloct