微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

一个类的一个属性调用另一个类的原型方法

如何解决一个类的一个属性调用另一个类的原型方法

直接进入代码,这里是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));

pos.plus()是哪里来的?

plus()方法Vec的原型中,对吗? pos如何访问plus()?它是Player类的属性,但是调用Vec类的方法。我很困惑。需要澄清。

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。