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();
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter