0

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)}
1

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.