如何在Javascript构造函数中初始化属性
How to initialize properties in Javascript constructor
我正在玩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));
}
}
由于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.
只需将该计算内联到构造函数中。
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/的工作示例。
你也可以写一个类似的函数来改变角度
相关文章:
- ng重复中的ng模型-初始化唯一作用域属性
- 每次属性更改时,角度控制器都会初始化
- 为什么我总是得到属性或字段尚未初始化
- 在初始化Javascript时执行的私有函数中设置公共属性
- 新Javascript对象的可选初始化属性
- 在object.defineProperty之前在对象初始化中设置属性
- 想要初始化“;min”;输入类型的属性=“;日期“;在HTML5中,具有特定日期格式的日期值
- 初始化可从元素属性值观察到的Knockout
- 在使用函数作为构造函数时,我在初始化属性时卡住了这个运算符.我的代码如下
- 如何在使用 AngularJS ng-repeat 时初始化本地范围内的属性
- Javascript 对象属性初始化
- 初始化时主干不休息属性值
- Javascript:按属性初始化对象
- Vue.js从 html 初始化对象属性
- 使用同一对象的其他属性初始化对象属性
- 余烬未正确初始化存储:无法读取未定义的属性“查找”
- 在 Backbone 中将函数设置为属性.js给了我一个错误,但如果我在初始化方法中设置它,它会起作用
- 获得'未定义'在原型的构造函数中初始化属性时
- 如何在Javascript构造函数中初始化属性
- 在Javascript中第一次访问时初始化属性