what is bind() method in javascript?

5 replies
  • WEB DESIGN
  • |
what is bind() method in javascript?
#bind #javascript #method
  • Profile picture of the author ynef
    bind()
    is used to bind the value of
    this
    to an object. In other words you can choose specifically which object will be bound to
    this
    so you can use it within your code.
    Signature

    Content writer, web developer, SEO consultant - Ynef's Portfolio

    {{ DiscussionBoard.errors[10273159].message }}
  • Profile picture of the author webcosmo
    It will bound ' this' value to the first argument of bind function. If you bind some object to another, this.var will become var of the binded object.
    {{ DiscussionBoard.errors[10273234].message }}
  • Profile picture of the author Sowkat Hossain
    The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
    eg.
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $("p").bind("click", function(){
    alert("The paragraph was clicked.");
    });
    });
    </script>
    </head>
    <body>

    <p>Click me!</p>

    </body>
    </html>
    {{ DiscussionBoard.errors[10275693].message }}
  • Profile picture of the author yasar
    bind value base on tha parameters, its like a function

    sysntex of bind method

    fun.bind(thisArg[, arg1[, arg2[, ...]]])

    where arg1 , arg 2 is a variable you put a values of those variables
    {{ DiscussionBoard.errors[10276611].message }}
  • Profile picture of the author Nimmy Wilson
    Bind creates a new function that will have this set to the first parameter passed to bind().


    Here's an example that shows how to use bind to pass a member method around that has the correct this:
    var Button = function(content) { this.content = content; }; Button.prototype.click = function() { console.log(this.content + ' clicked'); } var myButton = new Button('OK'); myButton.click(); var looseClick = myButton.click; looseClick(); // not bound, 'this' is not myButton var boundClick = myButton.click.bind(myButton); boundClick(); // bound, 'this' is myButton Which prints out:

    OK clicked undefined clicked OK clicked You can also add extra parameters after the 1st parameter and bind will pass in those values to the original function before passing in the extra parameters you pass to the bound function:
    // Example showing binding some parameters var sum = function(a, b) { return a + b; }; var add5 = sum.bind(null, 5); console.log(add5(10)); Which prints out:
    {{ DiscussionBoard.errors[10277938].message }}

Trending Topics