您好,这是我第一次尝试编写 JavaScript 应用程序,所以我是使用它编写 OOP 代码的新手。
以下代码在控制台中运行,没有任何错误:
// Main file for the application
$(document).ready( function()
{
var app = new application;
setInterval( app.run, 50 );
});
function application()
{
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.molecule.update(10);
this.run = function()
{
}
}
但是,这段代码不起作用:
// Main file for the application
$(document).ready( function()
{
var app = new application;
setInterval( app.run, 50 );
});
function application()
{
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.run = function()
{
this.molecule.update(10);
}
}
它在控制台中给出以下错误:
Uncaught TypeError: Object function molecule( pos,vel,canvas )
{
this.radius = 5;
this.color = "red";
this.canvas = canvas;
this.pos = pos;
this.vel = vel;
this.circle = canvas.circle( this.pos.x,this.pos.y,this.radius );
this.circle.attr("fill", this.color );
} has no method 'update'
这是包含分子对象的源文件。
// This 'class' handles a molecule, including movement and drawing.
function molecule( pos,vel,canvas )
{
this.radius = 5;
this.color = "red";
this.canvas = canvas;
this.pos = pos;
this.vel = vel;
this.circle = canvas.circle( this.pos.x,this.pos.y,this.radius );
this.circle.attr("fill", this.color );
}
// Updates the molecule
molecule.prototype.update = function( deltaTime )
{
this.pos += this.vel * deltaTime;
this.setPosition(this.pos);
}
// Accepts a Vec2
molecule.prototype.setPosition = function( pos )
{
this.circle.translate( pos.x-this.pos.x, pos.y-this.pos.y );
}
对于我发布的大量代码,我感到很抱歉,但我很困惑为什么第一段代码有效,而第二段代码无效。有人可以为我解释一下吗?非常感谢。