2016-03-01 347 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

相關問題