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

JS新手求助:页面加载实例化SinkShip类报Uncaught TypeError错误

解决TypeError: SinkShip is not a function的问题

问题根源

  1. 局部变量覆盖全局类
    在window.onload的回调函数里,你声明了let SinkShip;,这个局部变量会直接覆盖全局作用域中的SinkShip类。当执行new SinkShip()时,这里的SinkShip是未赋值的局部变量(值为undefined),自然不是构造函数,因此抛出错误。

  2. 初始化方法未调用
    构造函数里的this.initialies只是引用了方法,没有执行它,必须加上括号()才能触发方法执行。

修正后的代码

class SinkShip{
    constructor(){
        this.initialies(); // 调用初始化方法
    }

    initialies(){
        alert('it works');
    }
}

window.onload = (event)=>{
    console.log('HIIIII');
    // 移除局部的SinkShip声明,直接使用全局类
    const game = new SinkShip();
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:22:00