I'm new to javascript and am trying to create an object that I can then fill a list with instances of. This code I have works, but it feels redundant to have the "this." keyword on every line. Is there a neater/more appropriate way to create an object like this?
Here is my current object:
var Particle = function(x, y) {
this.x = x;
this.y = y;
this.xspeed = 0;
this.yspeed = 0;
this.xacc = 0;
this.yacc = 0;
this.update = function() {
this.x += this.xspeed;
this.y += this.yspeed;
this.xspeed += this.xacc;
this.yspeed += this.yacc;
}
}
Thanks for your assistance in advance
Unfortunately this is mandatory in Javascript, even if the other languages deduce it.
Today Ecmascript classes are supported by any browser excepting IE. It could be a good way to use class syntax if you want to use object oriented programming.
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.xspeed = 0;
this.yspeed = 0;
this.xacc = 0;
this.yacc = 0;
}
update() {
this.x += this.xspeed;
this.y += this.yspeed;
this.xspeed += this.xacc;
this.yspeed += this.yacc;
}
}
const particle = new Particle(1, 2);
particle.update();
console.log(particle);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With