I write a function to add listener to all elements match a specific selector, as below:
// Add event handler to all elements match a specific selector
function addEventListenerToAll(selector, type, listener)
{
[].forEach.call(document.querySelectorAll(selector), function(element) {
if (element) {
element.addEventListener(type, listener);
}
});
}
Then I invoke the function as below:
addEventListenerToAll(".myclass", "click", function () {
var url = this.getAttribute('myurl'); // What is 'this' refers to?
});
Then what is 'this' in this.getAttribute refers to?
Based on my test, it refers to one of the elements in the foreach loop. However, I check this document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this and it said in "Class context", 'this' in a non-static function refers to the current class object, otherwise, it defaults to the global object, in browser, it should be the window object.
So, as the listener function is not a class member function, it should refer to window instead?
CodePudding user response:
Functions can be given a different this
scope to what would be the default. You can do this yourself with the apply
method. (Edit: as @pilchard pointed out below, this doesn't apply to arrow functions, which inherit the parent scope.) In event listeners, the this
refers to the element the event listener was applied to (currentTarget
).