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>

其他回答

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

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

jQuery.proxy()

Dojo.hhitch()

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

变量具有局部和全局作用域。假设我们有两个同名的变量。一个是全局定义的,另一个是在函数闭包内定义的,我们希望得到函数闭包内的变量值。在这种情况下,我们使用这个bind()方法。请参见下面的简单示例:

变量x=9;//这是指浏览器中的全局“窗口”对象var人={x: 81中,getX:函数(){返回此.x;}};var y=person.getX;//它将返回9,因为它将调用x的全局值(varx=9)。var x2=y.bind(人);//它将返回81,因为它将调用在名为person(x=81)的对象中定义的x的局部值。document.getElementById(“demo1”).innerHTML=y();document.getElementById(“demo2”).innerHTML=x2();<p id=“demo1”>0</p><p id=“demo2”>0</p>

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

//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()的最简单用法是生成一个函数,无论它是如何被调用的。

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