Thanks for your post. Very interesting reading for all kind of developers.
In the past I used to use event.target a lot. Nowadays I'm trying to get more familiarized with the 'this' shortcut.
The way you capture the event in the callback is the same, but inside the function I use to write:
There are some considerations for you to have in mind when you use the 'this' inside a function. In my cases, I try to make sure that I'm dealing with something that can be accessed and handled with no problems (most of the time, it's an element within the DOM. I am still in the early begining of learning JS, I don't iterate over functions or some other 'complex' stuff). So for adding and managing event handlers or for iterate over the node list querySelectorAll returns, I'm kinda comfortable using 'this'
Any thoughts, recomendations or advices?
Thanks in advance
Thank you for the comment. I wasn’t aware of the exact behaviour of this in event handlers.
I tend not to use mechanisms like this because they make less explicit what I’m trying to do. Also, they cannot be used with ES6 arrow functions, because they always keep the this binding from their lexical context.
Thanks for your post. Very interesting reading for all kind of developers.
In the past I used to use event.target a lot. Nowadays I'm trying to get more familiarized with the 'this' shortcut.
The way you capture the event in the callback is the same, but inside the function I use to write:
mouseenterHandler(e) {
this.classList.add(/* ... */)
}
There are some considerations for you to have in mind when you use the 'this' inside a function. In my cases, I try to make sure that I'm dealing with something that can be accessed and handled with no problems (most of the time, it's an element within the DOM. I am still in the early begining of learning JS, I don't iterate over functions or some other 'complex' stuff). So for adding and managing event handlers or for iterate over the node list querySelectorAll returns, I'm kinda comfortable using 'this'
Any thoughts, recomendations or advices?
Thanks in advance
stackoverflow.com/a/21667010/7435195
You can find there insightful explanation regarding a problem you might face when using
this
Following that I'd recommend to read the links in the other comments.
Event bubbling is facinating! :)
Thank you for the comment. I wasn’t aware of the exact behaviour of
this
in event handlers.I tend not to use mechanisms like this because they make less explicit what I’m trying to do. Also, they cannot be used with ES6 arrow functions, because they always keep the
this
binding from their lexical context.@fgiraldi Kyle Simpson’s third “You Don’t Know JS” book (which can be read on GitHub for free) explains this in a lot of detail: github.com/getify/You-Dont-Know-JS...