2016-11-13 107 views
1

我對JavaScript比較新,我正在嘗試爲我正在開發的遊戲類型項目創建一個非常簡單的物理引擎。爲了做到這一點,我創建了我所理解的類,即可以爲每個對象創建新副本的類。問題是我希望能夠更新一個值,比如x位置,並且還可以更新諸如x中間位置(x在屏幕上的中心)。我知道這可以通過使用對象字面值和getter來實現,但是我希望能夠根據屏幕上的內容實時創建新對象,並且我無法弄清楚如何使用get來完成這項工作。這裏是什麼,我試圖做的總體思路:根據其他屬性更新JS「class」的屬性?

var object = function (xPos, yPos, width, height) { 
    this.xPos = xPos; 
    this.yPos = yPos; 
    function getXMid (xP) { return xP + width/2; } 
    this.xMid = getXMid (this.xPos); 
    function getYMid (yP) { return yP + height/2; } 
    this.yMid = getYMid (this.yPos); 
} 

var ball = new object (10, 20, 50, 50); 
ball.xPos = 50; 
console.log (ball.xMid); // want this to output 75 instead of 45 

回答

0

你改變一個屬性,並期待其他屬性進行更新,遺憾的是它不工作時的性能保持原始值的方式。

你可以使用getter和setter方法和功能更新其他屬性,當你設置的值

var object = function(xPos, yPos, width, height) { 
 
    this._xPos = xPos; 
 
    this._yPos = yPos; 
 
    this.recalc = function() { 
 
    \t this.xMid = getXMid(this.xPos); 
 
     this.yMid = getYMid(this.yPos); 
 
    } 
 
    
 
    Object.defineProperty(this, 'xPos', { 
 
     get: function() { 
 
      return this._xPos; 
 
     }, 
 
     set: function(v) { 
 
     \t this._xPos = v; 
 
     \t this.recalc(); 
 
     } 
 
    }); 
 

 
\t Object.defineProperty(this, 'yPos', { 
 
     get: function() { 
 
      return this._yPos; 
 
     }, 
 
     set: function(v) { 
 
     \t this._yPos = v; 
 
     \t this.recalc(); 
 
     } 
 
    }); 
 
    
 
    function getXMid(xP) { return xP + width/2; } 
 
    
 
    function getYMid(yP) { return yP + height/2; } 
 
    
 
    this.recalc(); 
 
} 
 

 
var ball = new object(10, 20, 50, 50); 
 
ball.xPos = 50; 
 
console.log (ball.xMid); // want this to output 75 instead of 45

+0

由於這似乎工作!我對這個setter的工作原理有點困惑。你使用的v參數來自哪裏? –

+0

setter獲得的唯一參數是設置值,所以'v'就是您設置'this.xPos = ***'到 – adeneo