JavaScript';绑定&x27;方法?

JavaScript';绑定&x27;方法?,javascript,function,bind,Javascript,Function,Bind,JavaScript中的bind()有什么用?bind创建一个新函数,该函数将强制函数中的this作为传递给bind()的参数 <pre> note: do not use arrow function it will show error undefined </pre> 下面的示例演示了如何使用bind传递具有正确this的成员方法: var myButton = { content: 'OK', click() { console.log(thi

JavaScript中的
bind()
有什么用?

bind创建一个新函数,该函数将强制函数中的
this
作为传递给
bind()
的参数

<pre> note: do not use arrow function it will show error undefined  </pre>
下面的示例演示了如何使用
bind
传递具有正确
this
的成员方法:

var myButton = {
  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
打印出:

OK clicked
undefined clicked
OK clicked
15
您还可以在第一个(
this
)参数之后添加额外的参数,
bind
将这些值传递给原始函数。以后传递给绑定函数的任何其他参数将在绑定参数之后传入:

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));
打印出:

OK clicked
undefined clicked
OK clicked
15
查看更多信息和互动示例

更新:ECMAScript 2015增加了对
=>
函数的支持
=>
函数更紧凑,不会从定义范围更改
指针,因此您可能不需要经常使用
bind()
。例如,如果您希望第一个示例中的
按钮上的函数将
单击
回调连接到DOM事件,则以下都是有效的方法:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use bind() to ensure 'this' is the 'this' inside click()
    element.addEventListener('click', this.click.bind(this));
  }
};
或:

或:


bind函数创建一个新函数,其函数体和它调用的函数体相同。它是用此参数调用的。为什么使用bind fun.:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用绑定乐趣。我们不能覆盖绑定乐趣。它只存储类的初始对象

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

  • 将“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函数可以用于另一个收取不同会费的成员。例如,罗斯·盖勒有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()
最简单的用法是生成一个函数,不管 它是如何调用的,用一个特定的
this
值调用

x=9;
变量模块={
x:81,
getX:函数(){
归还这个.x;
}
};
module.getX();//81
var getX=module.getX;
getX();//9,因为在本例中,“this”指的是全局对象
//创建将“this”绑定到模块的新函数
var boundGetX=getX.bind(模块);
boundGetX();//81
有关更多信息,请参阅此链接


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

执行类似服务的两个类似toolkit API方法:


我将从理论上和实践上解释绑定

javascript中的bind是一个方法——Function.prototype.bind.bind是一个方法。它在函数原型上被调用。此方法创建的函数体与调用它的函数体相似,但“This”指传递给bind方法的第一个参数。其语法为

     var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
例如:--

var checkRange=函数(值){
如果(值的类型!=“编号”){
返回false;
}
否则{
返回值>=this.minimum&&value
/**
*Bind是从Function.prototype继承的方法,与call和apply相同
*它基本上有助于在初始化过程中将函数绑定到对象的上下文
* 
* */
window.myname=“Jineesh”;
var foo=函数(){
返回this.myname;
};
//IE<8对此有问题,ecmascript 5支持
var obj={
我的名字:“约翰”,
fn:foo.bind(窗口)//绑定到窗口对象
}; 
console.log(obj.fn());//返回Jineesh
来自
函数.prototype.bind()

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

那是什么意思

嗯,让我们来看看这样的函数:

var logProp = function(prop) {
    console.log(this[prop]);
};
var Obj = {
    x : 5,
    y : 10
};
Obj.log = logProp.bind(Obj);
现在,让我们看一个像这样的对象:

var logProp = function(prop) {
    console.log(this[prop]);
};
var Obj = {
    x : 5,
    y : 10
};
Obj.log = logProp.bind(Obj);
我们可以像这样将函数绑定到对象:

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
这是可行的,因为我们将
This
的值绑定到对象
Obj


真正有趣的是,您不仅为
this
绑定了一个值,还为它的参数
prop
绑定了一个值:

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Obj.log
不同,我们不必传递
x
y
,因为我们在绑定时传递了这些值。

通过将参数绑定到值来创建新函数
bind
方法从另一个函数创建一个新函数,该函数具有一个或多个绑定到特定值的参数,包括隐式
参数

局部应用 这是的一个例子。通常我们提供一个函数及其所有参数,这些参数会产生一个值。这称为函数应用。我们将函数应用于其参数

高阶函数(HOF) 部分应用程序是(HOF)的一个示例,因为它生成的新函数具有更少的参数

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

函数倍数
<pre> note: do not use arrow function it will show error undefined  </pre>
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>
    </>
  );
}