bind
Mon Feb 10 2025 02:49:32 GMT+0000 (Coordinated Universal Time)
Saved by
@davidmchale
function app() {
const message = "Hello from App!";
// Function that will use `this` correctly
function showMessage() {
console.log(this.message);
}
const button = document.querySelector("button");
// Bind `this` inside the event listener to the `app` function
button.addEventListener("click", showMessage.bind({ message }));
}
// Initialize the app
app();
content_copyCOPY
Comments