我正在玩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));
}
}
@skyfoot請參閱我答案的最後一行。該部分是可選的添加,但可以(稍後)用來更改初始化的'Ball'類的'speed'屬性,而不創建新的實例。 –
我正在尋找好的和乾淨的解決方案,因爲下一步是更新速度,我想使用相同的功能。 – skyfoot
請注意,不能在沒有'new'關鍵字的情況下調用此類,因爲普通的函數調用將僅返回返回值或「undefined」,而不是「class」的實例。另一種初始化類的方法:'var test1 = new Ball; test1.setAngleAndVelocity(20);' –