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


当前回答

function.prototype.bind()接受Object。它将调用函数绑定到传递的Object,并返回相同的。当对象绑定到函数时,这意味着您将能够使用“this”关键字。

也可以说,

function.prototype.bind()用于提供/更改作用

让powerOfNumber=函数(数字){设乘积=1;for(设i=1;i<=this.power;i++){产品*=数量;}退货产品;}让powerOfTwo=powerOfNumber.bind({power:2});警报(powerOfTwo(2));让powerOfThree=powerOfNumber.bind({power:3});警报(powerOfThree(2));让powerOfFour=powerOfNumber.bind({power:4});警报(powerOfFour(2));

让我们试着理解这一点。

    let powerOfNumber = function(number) {
      let product = 1;
      for (let i = 1; i <= this.power; i++) {
        product *= number;
      }
      return product;
    }

这里,在这个函数中,这对应于绑定到函数powerOfNumber的对象。目前,我们没有任何函数绑定到此函数。

让我们创建一个函数powerOfTwo,它将使用上面的函数查找数字的二次幂。

  let powerOfTwo = powerOfNumber.bind({power:2});
  alert(powerOfTwo(2));

这里使用bind将对象{power:2}传递给powerOfNumber函数。

bind函数将此对象绑定到powerOfNumber(),并将以下函数返回给powerOfTwo。现在,powerOfTwo看起来,

    let powerOfNumber = function(number) {
      let product = 1;
        for(let i=1; i<=2; i++) {
          product*=number;
      }
      return product;
    }

因此,powerOfTwo将找到第二个电源。

请随意查看。

Javascript中的bind()函数

其他回答

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

第一部分的示例

使用St8从反应包中抓取

import { useState } from "react"

function st8() {
    switch(arguments.length) {
        case 0: return this[0]
        case 1: return void this[1](arguments[0])
        default: throw new Error("Expected 0 or 1 arguments")
    }
}


function useSt8(initial) {
    // this in st8 will be something like [state, setSatate]
    return st8.bind(useState(initial))
}

// usage
function Counter() {
  const count = useSt8(0);
  return (
    <>
      Count: {count()}
      <button onClick={() => count(0)}>Reset</button>
      <button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
    </>
  );
}

第二部分的示例

const add = (a, b) => a+b

someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5) 
add5(10) // 15

// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10) 
add10(5) // 15
/**
 * 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()创建一个新函数,即它返回给您的函数的新引用。

在该关键字后面的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%”