This question has already been answered:
- Loss of context call 5 responses
I was faced with this situation and for educational purposes it is interesting to understand how this works.
I assigned this.button.addEventListener variable addHandler and calling addHandler several times led to the fact that when I click on any place in the document, the events that I have hung up with this construct are triggered.
Why it works that way, I can not understand. Tell me.
class Button1 { constructor(button, value) { this.button = button; this.value = value; this.init(); } init() { this.button.addEventListener('click', () => { console.log(this.value) }) } } class Button2 { constructor(button, value) { this.button = button; this.value = value; this.init(); } init() { let addHandler = this.button.addEventListener; addHandler('click', () => { console.log(this.value) }) } } let button1 = document.getElementById('button_1'); let button2 = document.getElementById('button_2'); let button3 = document.getElementById('button_3'); let button4 = document.getElementById('button_4'); let button5 = document.getElementById('button_5'); let button6 = document.getElementById('button_6'); let newButton1 = new Button1(button1, 'п'); let newButton2 = new Button1(button2, 'а'); let newButton3 = new Button1(button3, 'в'); let newButton4 = new Button2(button4, 1); let newButton5 = new Button2(button5, 2); let newButton6 = new Button2(button6, 3); <p>Я думал сработает только событие кнопки, но срабатывает событие кнопки + события трех следующих кнопок. К тому же события трех кнопок срабатывае при клике на любом месте документа</p> <button id='button_1'>п</button> <button id='button_2'>а</button> <button id='button_3'>в</button> <p>При нажатии на одну, сработает функция всех</p> <button id='button_4'>1'</button> <button id='button_5'>2'</button> <button id='button_6'>3'</button>
window. - Igor