gpt4 book ai didi

javascript - 为什么 JavaScript bind() 调用反转函数的参数?

转载 作者:行者123 更新时间:2023-12-03 07:08:27 25 4
gpt4 key购买 nike

像这样绑定(bind)到 input 元素的 oninput 事件:

oninput: this.updateNote.bind(event, note)

其中 note 是一个简单对象 ({ completed: bool, text: string}),event 是 InputEvent。

我定义了 updateNote 如下:

updateNote(note, event) {
...
}

它以一种我无法解释的怪异方式工作。

与 bind() 调用相比,updateNote 的参数顺序相反,但 note 是正确的对象,事件是 InputEvent。

最佳答案

当你这样做的时候

this.updateNote.bind(event, note)   // (1)

你创建了一个函数 boundFunc,它接受任意数量的参数并调用 updateNote,其中 this 等于任何 event 变量恰好包含一个参数 note,其余参数传递给 boundFunc。所以它基本上是:

event = whatever

function boundFunc(...args) {
...updateNote.this = whatever...
updateNote(note, ...args)
}

现在,onInput 需要一个函数并使用一个参数调用它,event。由于这个函数恰好是我们的boundFunc,所以它被这样调用:

boundFunc(event)   // (2)

并且根据上面,“updateNote”是这样调用的

updateNote(note, event)

这解释了“颠倒”的事情。事实上,没有什么是逆转的。第 (2) 行中的“事件”与您在 bind 行 (1) 中使用的“事件”无关。 那个 可能包含一些垃圾,只要您不在“updateNote”中使用this,它就会丢失。

关于javascript - 为什么 JavaScript bind() 调用反转函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com