javascript - 一个类的一个属性调用另一个类的原型方法
问题描述
直接进入代码,这里是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
类的方法。我很困惑。需要澄清一下。
解决方案
您似乎对变量范围感到困惑。pos
传递给构造函数的参数Player
仅在构造函数本身中可见,尽管它也可以在实例上访问,因为构造函数设置了this.pos
. 但是,在create
方法中,是一个完全不同的方法参数,与构造函数中的pos
无关。pos
推荐阅读
- sqlite - 当获取数据的 Sqlite 数据库获取新数据时,如何更新 FutureBuilder?
- c - 在 C 中重定向标准错误
- node.js - 发送过多电子邮件时超出 Gmail API 配额限制
- python - cv2.imshow() 函数显示正确的图像,但在使用 cv2.imwrite() 函数保存时,它保存了所有黑色像素图像?
- statistics - 计算 ctr 时如何标准化印象偏差?
- swift - 如何扩展一个数组,其中元素是具有符合协议的元素的数组
- python - 动态调用参数大小未知的函数
- qemu - virsh 的问题 / 无法连接到 qemu
- r - R 错误 (JAGS) 无法将节点插入 alpha[1:284]。尺寸不匹配
- android - 使用 Rx 和 GIPHY 测试 ViewModel