首页 > 解决方案 > 一个类的一个属性调用另一个类的原型方法

问题描述

直接进入代码,这里是Player类。

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);

Vec班级:

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);
  }
}

我似乎无法理解这一点:

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

pos.plus()是从哪里来的?

plus()方法在原型中Vec,对吧?怎么可能pos接触到plus()?它是Player类的属性,但调用Vec类的方法。我很困惑。需要澄清一下。

标签: javascriptclassoopobjectprototype

解决方案


您似乎对变量范围感到困惑。pos传递给构造函数的参数Player仅在构造函数本身中可见,尽管它也可以在实例上访问,因为构造函数设置了this.pos. 但是,在create方法中,是一个完全不同的方法参数,与构造函数中的pos无关。pos


推荐阅读