My code works, but I was taught to bind 'this' to the event listener function. In my web component class constructor, I have a button in the shadow root. In the constructor I also added the click event listener on the button and went ahead and defined the on click function as an arrow function, ie this.clickHandler = (e) => {...}
. However, I did not bind 'this' to the event listener function, I just used this.button.addEventListener('click', this.clickHandler)
. The code seems to work fine, and, like many others before me I'm sure, I'm left needing a bit of guidance about binding 'this'. Many thanks.

- 11
- 5
-
If it works it means you don't need to bind – Konrad Nov 26 '22 at 05:27
-
3If it’s an arrow function, `this` will automatically point to the instance, so binding is not necessary. If `clickHandler` was a method, then you’d need to bind `this`. See [How does the “this” keyword work?](/q/3127429/4642212). – Sebastian Simon Nov 26 '22 at 05:27
-
It also depends if you use `this` inside of the handler – Konrad Nov 26 '22 at 05:29
1 Answers
Create test code to see all options:
<my-component></my-component>
<script>
customElements.define("my-component", class extends HTMLElement{
constructor(){
function element ({ tag, ...props} ) {
return Object.assign(document.createElement(tag), props);
}
super().attachShadow({mode:"open"})
.append(this.button = element({
tag : "button",
innerText : "click me!",
onclick : (evt) => this.clicked(evt,1) // 1
}));
this.button.addEventListener("click", (evt) => this.clicked(evt,2) ); // 2
this.button.addEventListener("click", this.clicked ); // 3
this.button.addEventListener("click", this.clicked.bind(this) ); // 4
}
clicked( evt, nr="no parameters!" ){
console.log(evt.type, nr , "scope:", this.nodeName);
}
})
</script>
The
onclick
Event Handler Property creates better readable code, IMHO;
but you can only assign one per elementCan create multiple
click
handlers on one element, and pass arguments.is for when you never want to access scope and parameters inside the class method
IMHO, Do not use it! Because junior team members don't understand why behaviour is different from normal class methods.(again IMHO) is oldskool notation, when you see it in code
- it indicates something special is going on
- or the developer is old and never learned or appreciated new fat-arrow syntax with lexical scope
- or the developer is inexperienced, and copy-pasted code
- or ...
Note: you can pass arguments with
bind
. But it will prepend them to the bound method;
That means inclicked(evt)
theevt
parameter now becomes your first argument... more confusion for juniors.
Very deep dive on 'this': How does the "this" keyword work, and when should it be used?

- 16,526
- 2
- 32
- 49