0
var colors = ['red', 'blue', 'green'];
var ps = document.querySelectorAll('p');
for(var i = 0; i < ps.length; i++){
    ps[i].addEventListener('click', function(){
        var j = 0;
        return function(){
            this.style.color = colors[j];
            j++;
            if(j == 3)
                j = 0;
        }
    })
}

I want to add click event on all my paragraphs so that they react independently on the click by chnging it's color

1 Answers1

0

Every function have it's own context (this). When you create new function it have it's own context. You can use arrow function - it does not have separate context and preserves one from parent inside. Or you can use bind to assign your new function some specific context. I'd strongly suggest you to use bind since arrow functions are hugely overused and it can be hard to understand what is happening.

EDIT: See more precise description of this in commend from @VLAZ - it's important

Mr. Hedgehog
  • 2,644
  • 1
  • 14
  • 18
  • 2
    "*Every function have it's own context (`this`)*" that's not true - [the value for `this` is determined at call time](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work), not at creation time. The same function can have different values for `this` depending on how it's executed. Aside from arrow functions. – VLAZ Feb 27 '21 at 09:01