使用绑定更改范围

Using bind to change scope

我想了解bind如何用于改变返回结果时执行的函数的范围。

  1. .bind 究竟是在什么地方执行的?
  2. 为什么 .bind 会影响在函数内执行的代码范围?

这是我的代码:

// 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)
});

我也尝试了下面的代码,但是bind()这里好像没有影响:

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

此 bind() 方法不是来自 jQuery,而是来自标准内置函数。 它的定义是:

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.

下面是一个示例代码来说明其行为:

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