Search code examples
javascriptclassoopobjectprototype

One property of a class calling another class' prototype method


Coming straight to the code, here's the Player class.

class Player {
  constructor(pos, speed) {
    this.pos = pos;
    this.speed = speed;
  }

  get type() { return "player"; }

  static create(pos) {
    return new Player(pos.plus(new Vec(0, -0.5)),
                      new Vec(0, 0));
  }
}

Player.prototype.size = new Vec(0.8, 1.5);

And the Vec class:

class Vec {
  constructor(x, y) {
    this.x = x; this.y = y;
  }
  plus(other) {
    return new Vec(this.x + other.x, this.y + other.y);
  }
  times(factor) {
    return new Vec(this.x * factor, this.y * factor);
  }
}

I just can't seem to understand this:

return new Player(pos.plus(new Vec(0, -0.5)),
                   new Vec(0, 0));

Where's pos.plus() is coming from?

plus() method is in the prototype of Vec, right? How can pos have access to plus()? It's a property of Player class, but calling the method of Vec class. I'm confused. Need some clarification.


Solution

  • It seems that you are being confused by variable scope. The pos argument passed to the constructor of Player is only visible in the constructor itself, although it can also be accessed on the instance since the constructor sets this.pos. However, in the create method, pos is an entirely different method parameter that has nothing to do with the pos in the constructor.