2012-08-27 21 views
0

這裏奇怪的問題是小提琴與類中的對象(約翰Resig的簡單的傳承)

這一個工程

http://jsfiddle.net/P72UR/

這一個沒有

http://jsfiddle.net/j86TA/1/

對不起我包含了太多的代碼,只是想盡可能接近地進行測試。

第二個是使用一個對象來保存x和y值。第一個不是。

這可能是一個函數綁定問題,但我不完全確定。

我有這樣的代碼:

(function createClouds() { 

     var Cloud = Class.extend({ 

      size: 0, 
      alpha: 0, 

      x: 0, 
      y: 0, 

      pos: { 
       x: 0, 
       y: 0 
      }, 

      init: function (x, y, size, alpha) { 

       this.x = x; 
       this.y = y; 
       this.size = size; 
       this.alpha = alpha; 

console.log(this.x) // this prints a random number. all good 

      }, 

      update: function (time) { 

      }, 

      draw: function (ctx) { 

       ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')'; 
       ctx.beginPath(); 
       ctx.fillRect(this.x, this.y, this.size, this.size); 
       ctx.closePath(); 
       ctx.fill(); 
      } 
     }); 

     sg.Cloud = Cloud; 

    })(); 

然後我基本上創建與畫布上隨意點此對象。

for (var i = 0; i < 20; i++) { 

     var x = sg.util.getRandomInt(0, sg.currentGame.width); 
     var y = sg.util.getRandomInt(0, sg.currentGame.height - 260); 
     var size = sg.util.getRandomInt(20, 200); 
     var alpha = sg.util.getRandomNumber(.1, .6); 

     sg.createEntity(new sg.Cloud(x, y, size, alpha)); 
    } 

sg.createEntity將此實體添加到數組;

然後我調用一個方法。

for (var i = 0; i < sg.entities.length; i++) { 
       sg.entities[i].draw(this.context); 
      } 

繪製所有實體。

上述工作正常。我得到隨機點。

如果我改變這個。

(function createClouds() { 

     var Cloud = Class.extend({ 

      size: 0, 
      alpha: 0, 

      x: 0, 
      y: 0, 

      pos: { 
       x: 0, 
       y: 0 
      }, 

      init: function (x, y, size, alpha) { 

       this.pos.x = x; 
       this.pos.y = y; 
       this.size = size; 
       this.alpha = alpha; 

console.log(this.pos.x) //this prints a random number; 
console.log(this.pos) //inspecting this object shows same points. 

      }, 

      update: function (time) { 

      }, 

      draw: function (ctx) { 

       ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')'; 
       ctx.beginPath(); 
       ctx.fillRect(this.pos.x, this.pos.y, this.size, this.size); 
       ctx.closePath(); 
       ctx.fill(); 
      } 
     }); 

     sg.Cloud = Cloud; 

    })(); 

回答

1

這是因爲.extend()使基本對象的淺拷貝,但.pos是一個對象,所以複製它會導致本身,而不是更多的引用新的實例。

以下是發生什麼事情一個小例子:

var a = { x: 0 }, b = a; 

b.x = 4; 

console.log(a.x); // prints 4 

我不知道如何解決它,但因爲它似乎並不像它是爲了妥善處理對象的屬性。

相關問題