When you use 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
});
jsFiddle: link
Note 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. The e.target is always the concrete element that received the click, descending from the element to which the event handler was tied if the click was triggered on it.
There is another parameter to take into account: bubbling
(or event propagation).
Notice 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
});
jsFiddle: link
In this case both event handlers are triggered because once the button receives the click it propagates the event to the parent elements, and firing their eventhandlers along that path. Also notice that the eventhandler of btn
fires first!.
This can be useful for distinguishing between this
and e.target
when you want to know in detail which element is clicked.