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


当前回答

bind函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。

setInterval(this.animate_to.bind(this), 1000/this.difference);

其他回答

考虑下面列出的简单程序,

//we create object user
let User = { name: 'Justin' };

//a Hello Function is created to Alert the object User 
function Hello() {
  alert(this.name);
}

//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();

//we create an instance to refer the this keyword (this.name);

bind()方法创建一个新的函数实例,该实例的值与传递到bind(的值绑定。例如:

   window.color = "red"; 
   var o = { color: "blue" }; 
   function sayColor(){ 
       alert(this.color); 
   } 
   var objectSayColor = sayColor.bind(o); 
   objectSayColor(); //blue 

在这里,通过调用bind()并传入对象o,从sayColor()创建了一个名为objectSayColor)的新函数。objectSayCcolor()函数的这个值相当于o,因此即使作为全局调用调用该函数,也会显示字符串“blue”。

参考资料:Nicholas C.Zakas-面向WEB开发人员的专业JAVASCRIPT®

简单解释:

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是一个在java脚本原型中可用的函数,因为名称建议bind用于将您的函数调用绑定到上下文,无论您正在处理什么,例如:

var rateOfInterest='4%';var轴库={利率:“10%”,getRateOfInterest:函数(){return this.rateOfInterest;}}axisBank.getRateOfInterest()//“10%”让我们知道AxisBankInterest=axsBank.getRateOfInterest//当您想将函数调用分配给变量时,我们使用此语法knowAxisBankInterest();//默认情况下,您将在此处获得“4%”的输出,该函数称为wrt全局上下文let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank)//因此这里我们需要将函数调用绑定到其本地上下文knowExactAxisBankInterest()//“10%”

我将从理论上和实践上解释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;