如何仅为特定对象类型扩展对象类型?我不希望使用 object.color() 与另一个库发生冲突。目前,我正在使用:
function random_int(start,end) {
return Math.floor(Math.random()*(end-start+1)+start);
}
var balls = function balls (context) {
this.canvas = context.canvas;
this.context = context;
}
Object.prototype.ball = function ball() { }
balls.prototype.add = function () {
this.context.fillStyle = '#ABC123';
this.radius = 15;
this.x = random_int(this.radius+1,this.canvas.width-this.radius-1);
this.y = random_int(this.radius+1,this.canvas.height-this.radius-1);
return this;
}
Object.prototype.draw = function () {
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, 0, (Math.PI/180)*360, false);
this.context.fill();
this.context.closePath();
}
balls.prototype.redraw = function () {
this.context.save();
this.context.setTransform(1, 0, 0, 1, 0, 0);
this.context.clearRect(0, 0, canvas.width, canvas.height);
this.context.restore();
this.draw();
}
Object.prototype.color = function (col) {
this.context.fillStyle = col;
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.canvas.width = window.innerWidth*0.9;
context.canvas.height = window.innerHeight*0.9;
var Balls = new balls(context);
for (var i = 0; i<10;i++) {
var b = Balls.add();
b.color("#"+((1<<24)*Math.random()|0).toString(16));
b.draw();
}
jsfiddle:http: //jsfiddle.net/hNy3r/1/
使用两个类,因为我计划稍后循环遍历 Balls 类中的每个球。