您好,這是我第一次嘗試編寫JavaScript應用程序,所以我不熟悉使用它編寫OOP代碼。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);
}
我對大量的我已經張貼代碼抱歉,但我難倒,爲什麼代碼的第一件工作,而第二個則不會。任何人都可以幫我解釋一下嗎?非常感謝。
非常感謝!我不熟悉它在JavaScript中的工作方式,只是希望能像其他語言一樣工作。 – 2013-02-16 20:59:25
@KarlJacques:你越早解脫自己的期望,就越好。如果所有的語言都一樣,那麼它們就不會是不同的語言。 – 2013-02-16 21:01:18