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

JS出现Uncaught SyntaxError: Unexpected strict mode reserved word报错如何解决

报错原因说明

你遇到的Uncaught SyntaxError: Unexpected strict mode reserved word报错属于语法错误,核心问题出在artist类的结构不符合JS语法规范:

  • ES6的类内部默认启用严格模式,类的顶层作用域仅允许声明成员(构造函数、方法、属性等),不允许直接写流程控制语句(如你的for循环)
  • 你把for循环直接放在artist类的顶层,还错误地用循环包裹了draw方法声明,JS解析到循环内的let关键字时,识别到这是严格模式下的保留字,且出现在了不符合语法规则的位置,因此抛出该错误。
其他可修复的代码问题

除了核心的类结构错误外,你的代码还有两处小问题:

  • background类中ctx.fillstyle拼写错误,Canvas API的属性是驼峰命名,应为ctx.fillStyle
  • 两处ctx.closePath调用都漏了括号,closePath是方法,需要写为ctx.closePath()
修复后的完整代码
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

class background {
  draw(){   
    ctx.fillStyle = 'green';
    ctx.beginPath();
    ctx.fillRect(0,10,800,500);
    ctx.fill();
    ctx.closePath();
  };
};

const Backdrop = new background();
Backdrop.draw();

class artist {
  draw(){
    // 循环逻辑移到draw方法内部
    for (let i = 0; i < 10; i++) {
      ctx.fillStyle = 'lime';
      ctx.beginPath();
      ctx.fillRect(0+i,10,20,15);
      ctx.fill();
      ctx.closePath();
    }
  };
};

const box = new artist();
box.draw();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:03