0
class Vector {
    constructor(x,y) {
      this.x = x || 0;
      this.y = y || 0;
    }

    add = function (c) {


        return new Vector(this.x + c.x,this.y+c.y)
    };


  }

I want to be able to do new Vector(4,4) + new Vector(0,2) --> Vector(4,6). Ive tried changing multiple parts and having a look but closest I found is old ES5 methods.

Evan Wrynn
  • 77
  • 6
  • 1
    You cannot overload the `+` operator. At most, you can change what primitive the instances are converted to when `+` is used but that will give you a primitive after the operation. You can make a method to handle the operation (as you've done here). – VLAZ Oct 02 '19 at 11:29
  • 4
    Unrelated, but doing `add = function(otherarray) {` here instead of `add(otherarray) {` is both longer and _less_ performant with zero benefits. – loganfsmyth Oct 02 '19 at 12:11

1 Answers1

1

Other answers have already pointed out that you can't overload operators in javascript, so what we can do is look into the add method you are using.

It looks like it isn't working because you aren't adding the values from the second Vector to the result.

You can try it like this:

add = function (otherVector) {
    return new Vector(this.x + otherVector.x, this.y + otherVector.y)
};