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


当前回答

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%”

其他回答

从Function.pr原型.bind()上的MDN文档中:

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

那是什么意思?!

好吧,让我们来做一个如下的函数:

var logProp = function(prop) {
    console.log(this[prop]);
};

现在,让我们看一个像这样的对象:

var Obj = {
    x : 5,
    y : 10
};

我们可以像这样将函数绑定到对象:

Obj.log = logProp.bind(Obj);

现在,我们可以在代码中的任何位置运行Obj.log:

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

这是有效的,因为我们将其值绑定到对象Obj。


它真正有趣的地方是,当你不仅为它绑定一个值,而且为它的参数属性绑定一个:

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

与Obj.log不同,我们不必传递x或y,因为我们在绑定时传递了这些值。

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

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

jQuery.proxy()

Dojo.hhitch()

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 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

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

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