使用绑定更改范围

问题描述 投票:0回答:1

我想了解如何使用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)}
javascript jquery bind
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.