You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何代码中用':'替代','会报错?Python+JS聊天机器人开发疑问

问题解答

报错原因与教程写法的差异

  • 你使用的document.querySelector(selectors: '.chatbox__button')这类写法不属于标准JavaScript/TypeScript语法,JS/TS本身不支持这种“命名参数”的传参形式,因此TypeScript编译器会抛出',' expected. ts(1005)错误。
  • 教程里的写法大概率是以下情况之一:
    • 作者演示时的笔误,漏写了对象的花括号(但即使补全花括号,querySelector这类原生DOM API也不接受对象参数);
    • 混淆了Python语法(Python支持func(parameter=value)的命名参数写法,但JS/TS不兼容);
    • 使用了特定框架、预处理器的语法糖,但这种语法在标准JS/TS环境下无法运行。

你的代码修正版本

querySelector和addEventListener都是标准DOM API,只需直接传递对应参数即可,不需要额外的命名标识:

class Chatbox {
     constructor() {
        this.args = {
           openButton: document.querySelector('.chatbox__button'),
           chatBox: document.querySelector('.chatbox__support'),
           sendButton: document.querySelector('.send__button'),
        }

        this.state = false; 
        this.messages = [];
     }

     display() {
        const {openButton, chatBox, sendButton} = this.args;

        openButton.addEventListener('click', () => this.toggleState(chatBox))

        sendButton.addEventListener('click', () => this.onSendButton(chatBox))

        const node = chatBox.querySelector('input');
        node.addEventListener("keyup", ({ key }) => {
             if (key == "Enter") {
                this.onSendButton(chatBox)
             }
        })
     }
}

补充说明

如果在JS中需要类似“命名参数”的效果,通常是通过对象解构实现自定义函数,示例如下:

// 自定义支持解构的函数
function handleEvent({ type, listener }) {
  // 逻辑处理
}
// 调用时传递对象
handleEvent({ type: 'click', listener: () => {} })

但这种方式仅适用于自定义函数,原生DOM API不支持此类传参。

内容的提问来源于stack exchange,提问作者user22081405

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:15:17