bind(), call() and apply()

930 0 0 0

Last Updated : 2024-05-01 23:02:16

In alot of cases in javascript, you will find it very difficult to pass certain parameter values or context to the function call. For example, the keyword 'this' which will mean very different things each time it is used depending on the context in which it was used and how it was used, inside a function or outside it, inside a function defined with the function keyword or an arrow function. Also when triggering an event that call a function and you need to pass/bind some parameters to this function. So here is a good explanation for the bind(), call() and apply() functions.


  1. bind()
    <button type="button" id="theButton">Click Me</button>;
    <div style="padding:10px;background-color:lightcoral;border: 2px solid gray;display: none;" id="theDiv"></div>;

    <script></script>;
    const theButton = document.getElementById('theButton');
    function showTheDiv(color) {
    const theDiv = document.getElementById('theDiv');
    theDiv.style.display = 'block';
    theDiv.style['background-color'] = color;

    console.log(color);
    }

    theButton.addEventListener('click', showTheDiv.bind(null, 'green));
    </script>?

    Mohammed Anwar

    Mohammed Anwar

    Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .