Blog>
Snippets

Binding 'this' with 'bind'

Use the 'bind' method to permanently associate a specific 'this' context to a function.
<button id='myButton'>Click Me</button>
HTML markup - a simple button with an ID of 'myButton'.
#myButton {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
CSS styles - styling the button with padding, font size, and a pointer cursor.
function ButtonHandler() {
    this.clicked = false;
    this.handleClick = function() {
        this.clicked = true;
        console.log('Button clicked:', this.clicked);
    };
}

// Create a new context for 'this'
var handler = new ButtonHandler();

// Get reference to the button element
var button = document.getElementById('myButton');

// Use 'bind' to permanently associate 'handler.handleClick' with 'handler'
button.addEventListener('click', handler.handleClick.bind(handler));
JavaScript code - Define a ButtonHandler constructor function, create an instance, and bind the instance's handleClick method to the click event on the button, ensuring 'this' refers to the handler object within the handleClick method.