Search code examples
javascriptjquerybind

Using bind to change scope


I would like to understand how bind is used to change the scope of the function that is executed when the result is returned.

  1. What is the .bind executed on exactly?
  2. Why would the .bind affect the scope of code that is executed within the function?

Here is my code:

// scope is window...
console.log(this)

// with bind -> scope is window...
$.get("https://api.github.com/users/octocat/gists", function(result) {
  var lastGist = result[0];
  console.log(this)
}.bind(this));

// without bind -> scope is $.get
$.get("https://api.github.com/users/octocat/gists", function(result) {
  var lastGist = result[0];
  console.log(this)
});

I also tried the following code, but bind() did not seem to have an impact here:

var a = function(){console.log(this)}.bind(this)    
var b = function(){console.log(this)}

Solution

  • This bind() method is not from jQuery but from standard build-in functions. Its defintion is :

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    Here is an example code to illustrate its behavior:

    this.x = 9; 
    var module = {
      x: 81,
      getX: function() { return this.x; }
    };
    
    module.getX(); // 81
    
    var getX = module.getX;
    getX(); // 9, because in this case, "this" refers to the global object
    
    // Create a new function with 'this' bound to module
    var boundGetX = getX.bind(module);
    boundGetX(); // 81