Здравствуйте, это моя первая попытка попытаться написать приложение 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, и просто ожидал, что это будет работать так же, как на других языках. –
@ KarlJacques: Чем скорее вы избавитесь от этого ожидания, тем лучше. Если все языки работают одинаково, то они не будут разными языками. –