2013-10-23 20 views
0

下面創建一個新的實例是我的代碼,無法在JavaScript

function hostile(x, y) { 
     this.speed = 1; 
     this.health = 100; 
     this.x = x; 
     this.y = y; 
     this.height = 32; 
     this.width = 32; 
     this.isDead = false; 
     this.direction = 0; 

     this.move = function(){ 
      context.clearRect(0,0,canvas1.width,canvas1.height); 
      if (this.x > canvas.width - 64) { 

       this.y += 10; 
       this.direction = 0; 
      } 
      if (this.x < 0) { 
       this.y += 10; 
     } 

      if (this.direction === 1) { 
       this.x += this.speed; 
     } else { 
       this.x -= this.speed; 
     } 
      if (this.x < 0) { 
       this.direction = 1; 
      } 

      if (this.y > 420) { 
      //this might have to be changed 
       this.x = 600; 
      } 
     } 
    }; 
//CREATING AN INSTANCE OF HOSTILE, THIS ISN'T WORKING FOR MULTIPLE INSTANCES, BUT WHY? 

var hostile = new hostile(20,20); 
var hostileA = new hostile(20,20); 

我有hostile創建,我有這樣的情況被稱爲在更新方法,hostile.move()但是VAR hostile工程,VAR hostile沒有,我檢查了代碼hostile是文件中的唯一參考。

+0

順便說一句,http://www.jshint.com/會爲你抓到這個。 – SLaks

回答

2
var hostile = new hostile(20,20); 

你只覆蓋了hostile變量來引用該實例,而不是構造函數。

這是構造函數按照慣例是UpperCamelCase的原因之一

1

你擦掉你的構造與

var hostile = new hostile(20,20); 

那麼你就不能創建其他敵對對象。