In my program using the function()
syntax is returning the this
value of a target element, but using an arrow function returns the window object. How are each of these two functions getting their this
?
function editTemplates() {
//sits within for loop
clocksTemplate.gmt[i].addEventListener('keydown', (e) => {
console.log(this); //returns window object
});
clocksTemplate.gmt[i].addEventListener('keydown', function(e) {
console.log(this); //returns element bound to clocksTemplate.gmt
});
According to MDN with arrow functions, this should "retain the original meaning from the enclosing context". Is the enclosing context the event listener? or the function it sits within? According to my test, the enclosing context for the arrow function must be the Window object but I can't see how. With the function() syntax the enclosing function is meant to redefine the this value, which I'm assuming it is doing here within the addEventListener
method. This topic has been discussed in depth here and here but I'm a JS newbie and I couldn't understand how this applied to my problem.