如何让addEventListener中setTimeout的this指向触发点击的单选按钮?
this Binding in Your setTimeout Callback Hey there! Let's sort out why your this isn't pointing to the "t-option" radio button, then walk through some reliable fixes.
The Problem
In your current code, the this inside the setTimeout callback doesn't refer to the radio button. That's because setTimeout runs its callback in the global execution context—by default, this will point to window (non-strict mode) or undefined (strict mode), not the element that triggered the click.
Solutions
Here are four straightforward ways to make sure myFunction gets the correct radio button reference:
1. Save this to a variable (classic, reliable approach)
Capture the element reference in a variable before setTimeout runs. This variable will retain the correct context:
document.getElementById("t-option").addEventListener("click", function () { const radioBtn = this; // Store the radio button element here setTimeout(function () { myFunction(radioBtn); // Use the stored reference instead of `this` }, 1500); });
2. Use an arrow function (modern, concise)
Arrow functions don't bind their own this—they inherit the this from the outer scope (which is the click event handler's this, pointing directly to the radio button):
document.getElementById("t-option").addEventListener("click", function () { setTimeout(() => { myFunction(this); // Arrow function inherits the correct `this` }, 1500); });
3. Use the event object's target property
The click event handler receives an event parameter, where e.target directly refers to the element that triggered the click. Save this reference to use later:
document.getElementById("t-option").addEventListener("click", function (e) { const targetBtn = e.target; setTimeout(function () { myFunction(targetBtn); }, 1500); });
4. Re-fetch the element (simple, but less flexible)
If the radio button's ID never changes and it stays in the DOM, you can re-select it inside the setTimeout callback. Note: This won't work if the element is removed/replaced dynamically:
document.getElementById("t-option").addEventListener("click", function () { setTimeout(function () { const radioBtn = document.getElementById("t-option"); myFunction(radioBtn); }, 1500); });
Recommendation
For most scenarios, options 1 or 2 are the best picks—they're clean, reliable, and scale well if you later add more similar radio buttons. Option 3 is ideal if you need event delegation or work with dynamic elements.
内容的提问来源于stack exchange,提问作者Nikos Tzoun

