2016-03-01 28 views
0

我正在用javascript制作游戏,并且我正在使用一个类来保存所有的精​​灵。但是,当我尝试运行它时,Safari会给我“SyntaxError:意外使用保留字'class'”。我找不到应该这样做的理由。下面是我的代码:为什么我在Javascript中使用“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; 
    } 

} 
+0

“一流”是一个新事物 - 您使用的是哪个版本的JavaScript引擎? – Soren

+0

这是ES6中的关键字。你用什么浏览器/环境? – zero298

+0

你不能在这样的类中声明函数,这是一个错误 – adeneo

回答

1

为了使您的代码的工作,更具体的关键字,你需要在严格的模式,以实现特定的浏览器来解释它。

要在严格模式下,添加以下到您的文件的顶部:

'use strict'; 
+1

澄清一点:语言本身并不需要'严格模式'来使用这些特性,但是将它们展开的浏览器已经启用了一些标准模式之前的模式。 –

+0

根据您的评论更新我的答案。谢谢。 – Sarhanis

+0

而且,至少Chrome是足够明智的,可以抛出像'..class尚未支持严格模式之外的错误',而不是'意外使用...' – adeneo

相关问题