未捕获的类型错误:回调时的非法调用

Uncaught TypeError: Illegal invocation on callback

本文关键字:回调 非法 调用 错误 类型      更新时间:2023-09-26
function submit() {
    console.log('Submit!');
}
function foo(callback, param) {
    console.log(callback);
    // ... //
    callback(param); // <-- Script fails here
}
<input type="button" onclick="foo(submit)">

为什么不工作?

function submit() { [native code] } foo.js:241
Uncaught TypeError: Illegal invocation 

内部事件属性(如onclick)有奇怪的作用域规则,我不会假装完全理解。

属性中的submit是输入所属表单元素的submit 属性

:

  • 显式传递window.submit
  • 将函数重命名为
  • 用JavaScript而不是HTML绑定你的事件处理程序。

根据一般原则,我自己会选择后一种方法(抓住机会停止使用全局变量),并考虑重命名函数以尽量减少混淆。

<input type="button">
<script>
    // Scoping IIFE omitted from this simplified example
    var button = document.getElementsByTagName('button')[0];
    button.addEventListener("click", function () { foo(submit); });
    function submit // etc etc
</script>