When using one or the other depends on what you want.
If you use for example:
<div>
<button onclick="clicaMe(event);">Clica-me!</button>
</div>
and in Javascript
var el = document.querySelector('div');
function clicaMe(e) {
console.log('inline this', this); // vai dar window
console.log('inline e.target', e.target); // vai dar button
}
el.onclick = function (e) {
console.log('onclick this', this); // vai dar el, ou seja "div"
console.log('onclick e.target', e.target); // vai dar button
}
el.addEventListener('click', function (e) {
console.log('event handler this', this); // vai dar el, ou seja "div"
console.log('event handler e.target', e.target); // vai dar button
});
Notice that when you run a function via onclick
inline in HTML the scope of this
will be window
. In other cases the this
is the very element that received the eventhandler or onclick. e.target is always the concrete element that received the click, descending from the element to which Event Handler was tied in case the click was triggered on it.
There is another parameter to take into account: bubbling
(or propagation of the event).
Look at this example:
var el = document.querySelector('div');
var btn = document.querySelector('button');
el.addEventListener('click', function (e) {
console.log('div this', this); // vai dar el, ou seja "div"
console.log('div e.target', e.target); // vai dar button
});
btn.addEventListener('click', function (e) {
console.log('button this', this); // vai dar button
console.log('button e.target', e.target); // vai dar button
});
In this case both Event handlers are fired because once the button receives the click it propagates the event to the parent elements, and firing its eventhandlers in that way. Note also that the eventhandler of btn
fire first!.
This can be something useful to distinguish between this
and e.target
when you want to know in detail which element clicked.
Related: http://answall.com/questions/51206/qual-a-diferen%C3%A7a-do-this-e-do-Event-target/51207#51207
– Wallace Maxters