如何在Javascript构造函数中初始化属性

How to initialize properties in Javascript constructor

本文关键字:初始化 属性 构造函数 Javascript      更新时间:2023-09-26

我正在玩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/的工作示例。

你也可以写一个类似的函数来改变角度