The bind Javascript method

Limited use but useful to know to avoid errors in callbacks.

Bind is mainly used in conjunction with a callback, and more precisely when the callback calls "this". Out of this case, it is anything but indispensable ... However, you may encounter the bind method in third-party codes, so it is useful to know what exactly it is used for.

Let's take an example. This script returns the name of a language when given a two-letter code. We simplify the demonstration with only two languages ...

var languages =  {
  a: function () {
    return "English";
  },

  b: function () {
    return "Français";
  },

  whatLang : function (x) {
    if(x == "en")
      return this.a();
    else
      return this.b();	
  }
}
document.write(languages.whatLang("en"));
Result

It should display "English" when the parameter is "en" or "French" when it is "fr".

Using a callback

We now decide to place in a callback the function that associates the code of two letters with the name of the language.

var languages =  {
  a: function () {
    return "English";
  },
	
  b: function () {
    return "Français";
  },
  
  whatLang : function (cback) {
    cback();
  },
	
  sel : function (x) {
    var l;
    this.whatLang(function() {
      if(x == "en")
        l = this.a();
      else
        l = this.b();
    });
    return l;	
  }
}
document.write(languages.sel("en"));
Result?

No results displayed and you can see in the console of the browser the error message "this.a is not a function".
The reason is that the callback creates a new context and this of the callback is not the this of the main function.
To remedy that, we add the bind method to the function in which the new this is used.

Adding bind

var languages =  {
  a: function () {
    return "English";
  },
	
  b: function () {
    return "Français";
  },
  
  whatLang : function (cback) {
    cback();
  },
	
  sel : function (x) {
    var l;
    this.whatLang(function() {
      if(x == "en")
        l = this.a();
      else
        l = this.b();
    }.bind(this));
    return l;	
  }
}
document.write(languages.sel("en"));
Result

This time the name of the language is well found because bind replaces this in the function by the one given in parameter and that one is the this of the main function.

Another solution would be to assign this in the function sel to a variable and use this variable instead of this in the function given as a parameter:

sel : function (x) {
  var l;
  var mainThis = this;
  this.whatLang(function() {
    if(x == "en")
      l = mainThis.a();
    else
      l = mainThis.b();
  });
 return l;	
}

This solution is also valid and maybe even easier to read. Bind can also be used with other parameters than this, it allows to transmit variables from a context to another without using global variables, which is safer.

© 22 novembre 2016 Xul.fr