Because JavaScript defines what variables a function can access by where the function is created, not by where it's called. If you want to provide information to a function from where it's called, you do that by passing it arguments instead.
Consider this example:
function handleInputEvents(selector) {
function showChange(value) {
console.log(`Value for "${selector}" changed to "${value}"`);
}
document.querySelector(selector).addEventListener("input", (event) => {
showChange(event.currentTarget.value);
});
}
handleInputEvents(".first");
handleInputEvents(".second");
<div>
<label>
First:
<input type="text" class="first">
</label>
</div>
<div>
<label>
Second:
<input type="text" class="second">
</label>
</div>
In that code, each call to handleInputEvents
creates a new showChange
function. The showChange
function uses two things:
selector
, which it can access because it was created where selector
is in scope, and
value
, which it can access because value
is a parameter of showChanges
; value
is provided by the caller as an argument
The showChanges
function wouldn't be able to access anything from where it's called (it can't access event
, for instance), but it can access things in scope where it was created.
Related: