bind()在JavaScript中的用途是什么?


当前回答

bind()的最简单用法是生成一个函数,无论它是如何被调用的。

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

有关详细信息,请参阅MDN Web Docs上的此链接:

函数.product.bind()

其他回答

我将从理论上和实践上解释bind

javascript中的bind是一种方法--Function.prototype.bind.bind是一个方法。它是在函数原型上调用的。此方法创建一个函数,其主体与调用该函数的函数相似,但“This”引用传递给绑定方法的第一个参数。其语法为

     var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);

示例:--

  var checkRange = function(value){
      if(typeof value !== "number"){
              return false;
      }
      else {
         return value >= this.minimum && value <= this.maximum;
      }
  }

  var range = {minimum:10,maximum:20};

  var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
  var result = boundedFunc(15); //passing value
  console.log(result) // will give true;

绑定允许-

将“this”的值设置为特定对象。这变得非常有用,因为有时这不是预期的。重用方法咖喱函数

例如,您有一个扣除每月俱乐部费用的功能

function getMonthlyFee(fee){
  var remaining = this.total - fee;
  this.total = remaining;
  return this.name +' remaining balance:'+remaining;
}

现在,您希望将此功能重新用于其他俱乐部成员。请注意,每个会员的月费会有所不同。

让我们想象一下Rachel的余额是500,每月会员费是90。

var rachel = {name:'Rachel Green', total:500};

现在,创建一个可以反复使用的函数,每月从她的账户中扣除费用

//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320

现在,相同的getMonthlyFee函数可以用于另一个具有不同会费的会员。例如,Ross Geller的余额为250,每月费用为25

var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200

简单解释:

bind()创建一个新函数,即它返回给您的函数的新引用。

在该关键字后面的parameter中,传递要预配置的参数。实际上,它不会立即执行,只是准备执行。

您可以根据需要预配置任意多个参数。

理解绑定的简单示例:

function calculate(operation) {
  if (operation === 'ADD') {
   alert('The Operation is Addition');
  } else if (operation === 'SUBTRACT') {
   alert('The Operation is Subtraction');
  }
}

addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));

Bind创建一个新函数,该函数将强制函数内部的this作为传递给Bind()的参数。

下面是一个示例,展示了如何使用bind传递具有正确this的成员方法:

var myButton = {
  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

打印结果:

OK clicked
undefined clicked
OK clicked

您还可以在第一个(this)参数之后添加额外的参数,bind将把这些值传递给原始函数。稍后传递给绑定函数的任何其他参数将在绑定参数之后传递:

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));

打印结果:

15

查看JavaScript函数绑定以获取更多信息和交互式示例。

更新:ECMAScript 2015增加了对=>函数的支持。=>函数更紧凑,不会从其定义范围更改this指针,因此您可能不需要经常使用bind()。例如,如果您希望第一个示例中Button上的一个函数将单击回调连接到DOM事件,以下都是实现这一点的有效方法:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use bind() to ensure 'this' is the 'this' inside click()
    element.addEventListener('click', this.click.bind(this));
  }
};

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use a new variable for 'this' since 'this' inside the function
    // will not be the 'this' inside hookEvent()
    var me = this;
    element.addEventListener('click', function() { me.click() });
  }
};    

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // => functions do not change 'this', so you can use it directly
    element.addEventListener('click', () => this.click());
  }
};

另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。

var name = "sample";
function sample(){
  console.log(this.name);
}
var cb = sample.bind(this);

function somefunction(cb){
  //other code
  cb();
}
somefunction.call({}, cb);