var Ball = function() {
function Ball(id, x, y, radius, speed) {
this.id = id;
this.x = x;
this.y = y;
this.radius = radius;
this.colours = newColours();
this.speed = speed;
var initialVector = {
x: Math.random() * 2 - 1,
y: Math.random() * 2 - 1
};
var vectorX = initialVector.x / Math.sqrt(initialVector.x * initialVector.x + initialVector.y * initialVector.y);
var vectorY = initialVector.y / Math.sqrt(initialVector.x * initialVector.x + initialVector.y * initialVector.y);
this.vector = {
x: vectorX,
y: vectorY
};
}
Ball.prototype.draw = function draw() {
cx.beginPath();
cx.arc(this.x, this.y, this.radius, 0, tau);
cx.fillStyle = 'rgba(' + this.colours.r + ',' + this.colours.g + ',' + this.colours.b + ', 1)';
cx.fill();
};
Ball.prototype.step = function step() {
this.x += this.vector.x * this.speed;
this.y += this.vector.y * this.speed;
this.checkBounds();
};
Ball.prototype.checkBounds = function checkBounds() {
if (this.x - this.radius <= 0) {
this.vector.x *= -1;
}
if (this.x + this.radius >= width) {
this.vector.x *= -1;
}
if (this.y - this.radius <= 0) {
this.vector.y *= -1;
}
if (this.y + this.radius >= height) {
this.vector.y *= -1;
}
};
return Ball;
}();
private
、static
等关键字控制可见性,所以只能用闭包来控制:不过现在已经有 ES6+ ,类的写法更加规范,就不必使用这些奇技淫巧了。