JavaScript中的面向对象编程与Canvas
看看JavaScript中的面向对象编程在不同情况下可以有多么有用... 这让你可以将正方形和圆形作为对象
绘制,以便您可以返回并循环或操纵它们。
function Shape(x,y,color){
this.x = x
this.y = y
this.color = color
}
function Square(height,width,color){
Shape.call(this, event.x, event.y, color)
this.height = height
this.width = width
this.x -= canvas.offsetLeft + (this.height/2)
this.y -= canvas.offsetTop + (this.width/2)
}
Square.prototype = new Shape();
Square.prototype.draw = function(color){
ctx.fillStyle = color
ctx.fillRect(this.x,this.y,this.height,this.width)
}
function Circle(color, width){
Shape.call(this)
this.x = event.x -60
this.y = event.y -60
this.width = width
}
Circle.prototype = new Shape();
Circle.prototype.draw = function(color){
ctx.beginPath()
ctx.arc(this.x,this.y,this.width,0,2*Math.PI, false);
ctx.fillStyle = color
ctx.fill()
}
bar
将成为全局对象的属性 (window.bar
),因为它没有在foo
函数的作用域中使用var
语句进行声明。此外,在 ECMAScript 5 严格模式下,这将导致ReferenceError
错误,因此请始终使用var
来 声明 变量 ;) - Christian C. Salvadófoo
的实例。 - casablanca