为什么在使用" class"时会出现语法错误?在Javascript中

时间:2016-03-01 02:31:31

标签: javascript class

我正在使用javascript制作游戏,我正在使用制作一个类来保存所有精灵。但是,当我尝试运行它时,safari会给我"语法错误:意外使用保留字' class'"。我无法找到应该这样做的理由。以下是我的代码:

var spritesContext;

//Sprite class
class sprite{
    constructor(imageName, imageX, imageY, imageHeight, imageWidth, context, canvas){
        this.imageName = imageName;
        this.imageX = imageX;
        this.imageY = imageY;
        this.imageHeight = imageHeight;
        this.imageWidth = imageWidth;
        this.canvas = canvas;
        this.context = context;
        spritesContext = context;
        console.log("Sprite constructed");
    }

    draw(){
        var character = new Image();
        character.src = "../Images/" + this.imageName + ".png";
        character.onload = function(){
            spritesContext.drawImage(character, this.imageX, this.imageY, this.imageWidth, this.imageHeight);
            console.log("Inner Draw is working.");
        }
        console.log("Draw is working.");
    }

    function getHeight(){
        return this.imageHeight;
    }

    function getWidth(){
         return this.imageWidth;
    }

    function getX(){
        return this.imageX;
    }

    function getY(){
       return this.imageY;
    }

    function moveUpX(e){
        this.imageX = (this.imageX + e);
    }

    function moveUpY(e){
        this.imageY = (this.imageY + e);
    }

    function moveBackX(e){
        this.imageX = (this.imageX - e);
    }

    function moveBackY(e){
       this.imageY = (this.imageY - e);
    }

    function changeImage(e){
        this.imageName = e;
    }

    function getImage(){
       return this.imageName;
    }

    function changeX(e){
         this.imageX = e;
    }

    function changeY(e){
        this.imageY = e;
    }

}

2 个答案:

答案 0 :(得分:1)

要使代码正常工作,更具体地说是关键字 class ,您需要处于严格模式,以使某些浏览器能够解释它。

要处于严格模式,请将以下内容添加到文件顶部:

'use strict';

答案 1 :(得分:0)

enter image description here

询问该问题时,Safari不支持“类”。