bind 参数

bind参数

在 JavaScript 中,Function.prototype.bind​ 方法用于创建一个新的函数,并将指定的参数预设到原函数中。它的语法如下:

function.bind(thisArg, arg1, arg2, ...)

参数解析

  1. thisArg​:

    • 这是新函数调用时的 this​ 值。
    • 如果不需要修改 this​,可以传入 null​ 或 undefined​。
  2. arg1, arg2, ... ​:

    • 这些是预设的参数,会按照顺序作为新函数的第一个、第二个参数等。
    • 在调用新函数时,这些参数会优先传递给原函数。

在你的代码中的具体应用

原始代码:

document.addEventListener('keydown', keydown.bind(null, topmostBtn));

function keydown(topmostBtn, event) {
    const label = topmostBtn.querySelector('.b3-menu__label');
    if (label && label.textContent === '置顶') {
        label.textContent = '置顶到顶级';
    }
}

解析:

  1. bind(null, topmostBtn) ​:

    • null​ 是 thisArg​,表示新函数调用时的 this​ 值为 null​(在这里我们不需要使用 this​)。
    • topmostBtn​ 是第一个预设参数,会被绑定到 keydown​ 函数的第一个参数位置。
  2. keydown的参数顺序:

    • keydown​ 函数定义为 function keydown(topmostBtn, event)​,因此:

      • 第一个参数是 topmostBtn​(通过 bind​ 预设)。
      • 第二个参数是 event​(由事件监听器自动传递)。
  3. 事件监听器的行为:

    • keydown​ 事件触发时,addEventListener​ 会自动将事件对象 event​ 作为参数传递给回调函数。

    • 由于 bind​ 已经预设了 topmostBtn​,最终的调用顺序如下:

      keydown(topmostBtn, event);
      

总结:参数的顺序

  • bind​ 的第一个参数(thisArg​)决定了新函数调用时的 this​ 值。
  • bind​ 的后续参数(如 topmostBtn​)会依次作为新函数的前几个参数。
  • 事件监听器自动传递的参数(如 event​)会追加到预设参数之后。

因此,在你的代码中:

  • topmostBtn​ 是 keydown​ 的第一个参数(通过 bind​ 预设)。
  • event​ 是 keydown​ 的第二个参数(由事件监听器自动传递)。

扩展:多个预设参数的示例

如果你需要预设多个参数,可以通过 bind​ 传递更多值。例如:

function example(param1, param2, event) {
    console.log('param1:', param1);
    console.log('param2:', param2);
    console.log('event:', event);
}

const newFunction = example.bind(null, '预设值1', '预设值2');
document.addEventListener('keydown', newFunction);

运行结果:

  • 当按下键盘时,控制台输出:

    param1: 预设值1
    param2: 预设值2
    event: KeyboardEvent {...}
    

希望这能帮助你更清楚地理解 bind​ 的参数机制!如果有其他问题,请随时提问。

image.png

留下你的脚步
推荐阅读