When to use .bind() in JS

后端 未结 3 1937
花落未央
花落未央 2020-12-06 12:49

There is a ton of blogs and posts about how to use bind() and how it\'s different than call() and apply(), but there is very little ex

3条回答
  •  生来不讨喜
    2020-12-06 13:34

    Use bind() when you want a function that always runs with a specific this value.

    It's useful for more functional programming, when passing around functions as callbacks or event handlers.

    var User = function(name) { this.name = name; };
    User.prototype.poke = function() { alert "Hey, don't poke " + this.name; };
    var bob = User('Bob');
    
    // assume jQuery for brevity, and because it screws with `this` in callbacks
    $('#some-element').click(bob.poke.bind(bob));
    

    This will alert "Hey, don't poke Bob" because you passed it a bound function. So if that element, was explicitly about Bob, it makes sense to bind the event handler to him.


    But there are other ways to do this without bind, of course.

    $('#some-element').click(function() {
      bob.poke();
    });
    

    The difference can be a matter of style. And bind didn't use to have lots of support in all browsers, so lots of JS programmers figured out other ways to do it, and lots of those other ways are still in use today.


    One clear win is when you want to pass the same function around to many different places, and you want an explicitly set this.

    var bobPoke = bob.poke.bind(bob);
    
    onFoo(bobPoke);
    onBar(bobPoke);
    onBaz(bobPoke);
    

提交回复
热议问题