Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript better way to create object with a method using function

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

like image 648
Adam S Avatar asked Aug 17 '26 13:08

Adam S


1 Answers

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);
like image 127
Benjamin Caure Avatar answered Aug 20 '26 02:08

Benjamin Caure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!