【问题标题】:Uncaught SyntaxError: Unexpected token = in ChromeUncaught SyntaxError: Unexpected token = in Chrome
【发布时间】:2015-04-01 08:32:52
【问题描述】:

我正在按照在线教程使用画布和 JavaScript 创建一个简单的 HTML 游戏。我尝试加载看似完美的代码,但屏幕上没有显示任何内容,并且我在控制台中收到错误提示

Uncaught SyntaxError: Unexpected token =

这是我的代码中似乎不正确的部分:

player = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        update = function() {},
        draw = function() {
            ctx.fillRect(this.x, this.y, this.width, this.height)
        };
    };

PS - 这个错误出现在 Chrome 中。

【问题讨论】:

  • 您绝对应该向我们展示上一行 - 下一行
  • 我不知道你的确切代码,但我在谷歌上找到了这个stackoverflow.com/questions/19699257/…
  • 我刚刚看了那个页面,但我还是不知道该怎么办!

标签: javascript canvas


【解决方案1】:

您在文字对象定义中使用= 符号,只需将它们替换为:

    update : function() {},
    draw : function() {
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }

正如amtd 在他的回答中指定的那样,在draw 定义之后会出现另一个错误,因为您在文字对象定义中放置了一个额外的; 非法标记

【讨论】:

    【解决方案2】:

    将函数设置为对象的属性时,您仍然需要使用: 声明它们,而不是=

    您也不需要在函数之后添加;,因为一旦修复了: 问题,您就会报错。

    player = {
        x: null,
        y: null,
        width: 20,
        height: 100,
        update : function() {},
        draw : function() {
            ctx.fillRect(this.x, this.y, this.width, this.height)
        }
    };
    

    【讨论】:

    • 还需要去掉draw函数中的分号 player = { x: null, y: null, width: 20, height: 100, update : function() {}, draw : function( ) { ctx.fillRect(this.x, this.y, this.width, this.height) } };
    猜你喜欢
    • 2013-11-11
    • 2019-03-18
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多