【问题标题】:Javascript bind extra paramsJavascript绑定额外参数
【发布时间】:2021-05-04 10:38:04
【问题描述】:

我需要将运行时参数传递给函数。我正在使用bind 将函数绑定到参数。但是,当调用函数时,运行时参数不可用。设置类似于以下:

const testFunction = (event, message) => {
  console.log(message); //message is undefined
}
const bindTheMessage = () => {
  testFunction.bind(document.getElementById('testButton'), 'hello');
}
<html>
<body>
  <button id='bindButton' onclick='bindTheMessage()'>bind a message</button>
  <button id='testButton' onclick='testFunction()'>click to get message</button>
</body>
<html>

有人可以帮忙吗?

【问题讨论】:

  • bind 不会改变函数对象,它会返回一个新函数。
  • 你的论点的顺序似乎错误 - 你想将'hello'绑定为message吗?

标签: javascript apply call bind


【解决方案1】:

你有两个问题。

它不会变异

bind 返回一个函数,它使用某些参数调用原始函数。

它不会改变原始函数。

你需要类似的东西:

testFunction = testFunction.bind(...)

为此(然后多次单击bindTheMessage 会继续嵌套它)

你错过了一个论点

documentation for bind

bind(thisArg, arg1, ... , argN)

第一个参数是this 值。后续参数是参数值。

您已将按钮元素绑定到this'hello'event,但没有绑定到message

【讨论】:

    【解决方案2】:

    从您所在的位置到您想要的结果的最短路径概述如下。您需要搁置testFunction.bind 返回的函数,并使用that 函数作为您的事件处理程序,而不是原来的testFunction,它不会通过调用bind 来改变。

    如果您想设置 event 参数,您还需要将 event 传递给您的函数,并且这需要是函数的最后一个参数,以便您绑定前两个参数。

    let boundTestFunction
    
    const testFunction = (message, event) => {
      console.log(message);
      console.log(event);
    }
    const bindTheMessage = () => {
      boundTestFunction = testFunction.bind(document.getElementById('testButton'), 'hello');
    }
    <html>
    <body>
      <button id='bindButton' onclick='bindTheMessage()'>bind a message</button>
      <button id='testButton' onclick='boundTestFunction(event)'>click to get message</button>
    </body>
    <html>

    说了这么多,我不会在这里使用内联事件处理程序。我会做如下的事情:

    const testFunction = (message, event) => {
      console.log(message);
      console.log(event);
    }
    
    document.getElementById("bindButton").addEventListener("click", function() {
      document.getElementById("testButton").addEventListener("click", testFunction.bind(document.getElementById('testButton'), 'hello'));
    })
    <html>
    <body>
      <button id='bindButton'>bind a message</button>
      <button id='testButton'>click to get message</button>
    </body>
    <html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-13
      • 2011-05-24
      • 2012-11-16
      • 1970-01-01
      • 2013-01-17
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多