我正在玩html5画布来创建弹跳球。我这一切都工作但我必须调用初始化函数来设置某些属性。如何在构造函数中自动执行此操作而不会在访问属性时触发初始化程序?
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));
}
}
答案 0 :(得分: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.
答案 1 :(得分: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/。
您还可以为角度更改编写类似的功能。