如何解决一个类的一个属性调用另一个类的原型方法
直接进入代码,这里是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 举报,一经查实,本站将立刻删除。