使用bind来改变范围

时间:2015-02-15 02:59:10

标签: javascript jquery bind

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

  1. 究竟是什么执行了.bind?
  2. 为什么.bind会影响函数内执行的代码范围?
  3. 非常感谢任何帮助,谢谢!

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

1 个答案:

答案 0 :(得分:1)

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

  

bind()方法创建一个新函数,当被调用时,它具有它   此关键字设置为提供的值,具有给定的序列   调用新函数时提供的任何参数。

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

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