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


当前回答

通过将参数绑定到值来创建新函数

bind方法从另一个函数创建一个新函数,其中一个或多个参数绑定到特定值,包括隐式this参数。

局部应用

这是部分应用的示例。通常,我们提供一个函数及其所有参数,这些参数会产生一个值。这就是所谓的函数应用程序。我们正在将函数应用于其参数。

高阶函数(HOF)

部分应用程序是高阶函数(HOF)的一个例子,因为它生成了一个新函数,但参数数量较少。

绑定多个参数

可以使用bind将具有多个参数的函数转换为新函数。

函数乘法(x,y){返回x*y;}让multiplyBy10=multiply.bind(null,10);控制台日志(multiplyBy10(5));

从实例方法转换为静态函数

在最常见的用例中,当使用一个参数调用时,bind方法将创建一个新函数,该函数将此值绑定到特定值。实际上,这将实例方法转换为静态方法。

函数乘数(因子){this.factor=系数;}Multiplier.prototype.multiply=函数(x){返回this.factor*x;}函数ApplyFunction(func,value){返回func(值);}var mul=新乘数(5);//生成垃圾(NaN),因为将“undefined”乘以10console.log(ApplyFunction(多个,10));//产生预期结果:50console.log(ApplyFunction(多乘绑定(多),10));

实现有状态回调

以下示例显示了如何使用this的绑定使对象方法充当回调,从而可以轻松更新对象的状态。

函数ButtonPressedLogger(){此计数=0;this.onPressed=函数(){这个.计数++;console.log(“按下按钮”+this.count+“次数”);}for(let d of document.getElementsByTagName(“button”))d.onclick=this.onPressed.bind(this);}new ButtonPressedLogger();<button>按我</button><button>不按我</button>

其他回答

/**
 * Bind is a method inherited from Function.prototype same like call and apply
 * It basically helps to bind a function to an object's context during initialisation 
 * 
 * */

window.myname = "Jineesh";  
var foo = function(){ 
  return this.myname;
};

//IE < 8 has issues with this, supported in ecmascript 5
var obj = { 
    myname : "John", 
    fn:foo.bind(window)// binds to window object
}; 
console.log( obj.fn() ); // Returns Jineesh

绑定允许-

将“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是一个在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中称为函数借用。

如上所述,Function.bind()允许您指定函数将在其中执行的上下文(也就是说,它允许您传递this关键字将解析到函数体中的对象)。

执行类似服务的两个类似工具包API方法:

jQuery.proxy()

Dojo.hhitch()