2011-09-24 47 views
0

我正在玩HTML5畫布來創建彈跳球。我有這一切工作,但我必須調用初始化函數來設置某些屬性。如何在構造函數中自動執行此操作,而不會在訪問屬性時觸發初始化器?如何在JavaScript構造函數中初始化屬性

var test1 = new Ball(20); 
test1.setAngleAndVelocity(); //I dont want to have to call this. 

function Ball(speed){ 
    this.position = new Vector2(canvas.width/2, canvas.height/2); 
    this.velocity; 
    this.speed = speed; 
    this.angle; 
    this.setAngleAndVelocity = function(){ 
     this.angle = Math.floor(Math.random() * 360) * 0.0174532925; 
     this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); 
    } 
} 

回答

4

由於setAngleAndVelocity()是一個靜態方法,我建議你把它放在你的Ball類的原型:

function Ball(speed){ 
    this.position = new Vector2(canvas.width/2, canvas.height/2); 
    this.speed = speed; 
    this.setAngleAndVelocity(); //Sets the additional values 
} 
Ball.prototype.setAngleAndVelocity = function(speed){ 
    speed = typeof speed != "undefined" ? speed : this.speed; 
    this.angle = Math.floor(Math.random() * 360) * 0.0174532925; 
    this.velocity = new Vector2(speed/10 * Math.cos(this.angle), speed/10 * Math.sin(this.angle)); 
} 

this.velocity;this.angle;是沒有必要的:他們不是什麼定義,而唯一他們所使用的用途是向開發人員展示可以定義哪些屬性。

這些修改之後,你的腳本已經變得更有效率,並能以這種方式使用:

var test1 = new Ball(20); //Inititalized 
test1.setAngleAndVelocity(22); //Optional, a method to adjust the speed value after the init of the class. 
+0

@skyfoot請參閱我答案的最後一行。該部分是可選的添加,但可以(稍後)用來更改初始化的'Ball'類的'speed'屬性,而不創建新的實例。 –

+0

我正在尋找好的和乾淨的解決方案,因爲下一步是更新速度,我想使用相同的功能。 – skyfoot

+0

請注意,不能在沒有'new'關鍵字的情況下調用此類,因爲普通的函數調用將僅返回返回值或「undefined」,而不是「class」的實例。另一種初始化類的方法:'var test1 = new Ball; test1.setAngleAndVelocity(20);' –

1

只是內聯計算到構造。

function Ball(speed){ 
    this.position = new Vector2(canvas.width/2, canvas.height/2); 
    this.speed = speed; 
    this.angle = Math.floor(Math.random() * 360) * 0.0174532925; 
    this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); 
} 

附錄

如果你想保持功能在你的周圍應用程序更新在其他時間的角度和速度,把該函數原型:

Ball.prototype.changeSpeed = function (newSpeed) { 
    this.speed = newSpeed; 
    this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); 
} 

如果您願意,您可以從構造函數中調用此方法:

function Ball(speed){ 
    this.position = new Vector2(canvas.width/2, canvas.height/2); 
    this.angle = Math.floor(Math.random() * 360) * 0.0174532925; 
    this.changeSpeed(speed); 
} 

查看http://jsfiddle.net/FnHLX/作爲一個工作示例。

您還可以編寫一個類似的角度變化函數。

+0

關於你提到的增編,我怎麼叫changeSpeed在構造函數中。我不想讓代碼重複。 – skyfoot

+0

@skyfoot,當然你不想複製那些代碼!你可以從構造函數中調用。我做了一個小提琴http://jsfiddle.net/FnHLX/,並會立即更新答案。好眼睛! –

相關問題