0

Program:

<html>
...

<button class="accordion">Section 1</button>
<div class="panel"> <p> .... </p> </div>

<button class="accordion">Section 2</button>
<div class="panel"> <p> .... </p> </div>

<button class="accordion">Section 3</button>
<div class="panel"> <p> .... </p> </div>

<script>
        var acc = document.getElementsByClassName("accordion");
        var i;

        for (i = 0; i < acc.length; i++) {
            acc[i].onclick = function(){
                this.classList.toggle("active");
                this.nextElementSibling.classList.toggle("show");
          }
        }
</script>
...
</html>

I am a newbie to javascript. So, I am not able to understand the above javascript code. I expect "this" keyword refers to window object. Because, it is called within anonymous function and also there is no object for that function. But, it refers to the object "HTMLButtonElement". How "this" refers to Button object ?

mohangraj
  • 9,842
  • 19
  • 59
  • 94
  • 1
    The `this` keyword is set based on execution context, which in this case is an event handler, and event handlers has the element as context. – adeneo May 31 '16 at 10:33
  • Possible duplicate of [How does "this" keyword work within a JavaScript object literal?](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal) – nagyben May 31 '16 at 10:34

3 Answers3

1

How "this" refers to Button object ?

Every function has its own scope, its own this reference.

 acc[i].onclick = function(){
            this.classList.toggle("active");
            this.nextElementSibling.classList.toggle("show");
      }

This function is an event handler on acc[i] which is a button with class accordion. So, this is pointing to the DOM object pointing towards HTMLButtonElement pointing towards acc[i]

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

this keyword basically refers to the current object it is playing a role here as a event handler

Pooja
  • 39
  • 9
0

this refers to current execution context and in your case its button. If you want it to refer to window, keep a reference of it and then use it inside your onClick handler.

If you run the fiddle, you could see the results.

 var acc = document.getElementsByClassName("accordion");
        var i; 
        var that = this;
        for (i = 0; i < acc.length; i++) {
            acc[i].onclick = function(){
                alert(this);
                alert(that);
                this.classList.toggle("active");
                this.nextElementSibling.classList.toggle("show");
          }
        }

https://jsfiddle.net/g1s0r9as/

Thalaivar
  • 23,282
  • 5
  • 60
  • 71