为什么一个对象的方法不适用于另一个对象

Why is an object's method not available for another object?

本文关键字:一个对象 适用于 不适用 方法 为什么      更新时间:2023-09-26
function Vector(i, j, k){
    this.i = i;
    this.j = j;
    this.k = k;
};
Vector.prototype = {
    addition: function(vec){
        return new Vector(vec.i+this.i, vec.j+this.j, vec.k+this.k);
    },
    magnitude: function(){
        return Math.sqrt(this.i*this.i + this.j*this.j + this.k*this.k);
    },
};
function Orbit(rp, ra, ecc){
    this.rp = new Vector(rp, 0, 0);
    this.ra = new Vector(ra, 0, 0);
    this.a = this.rp.addition(this.ra).magnitude(); //The error is in this line
};
var orbit = new Orbit(6563, 42165);

所以我在这里要做的是为rp创建Vector对象,raOrbit对象中。 a应该利用向量rpra的原型方法,但是当我运行脚本时,rp的原型方法不可用,并且我收到一个错误说:

TypeError: 'undefined' is not a function (evaluating 'this.rp.addition(this.ra)')

我希望这不是我在某个地方遗漏的愚蠢错误,因为这已经给我带来了一段时间的麻烦。这是我第一次在JS中使用原型,所以我看不出我在这里做错了什么。我只需要知道为什么this.rp没有Vector方法以及我可以做些什么来修复我的代码。

问题不在于你认为它在哪里。

this.a构建为:

this.a = this.rp.addition(this.ra).magnitude(); 

这意味着它是一个数字,所以你不能接受this.a.magnitude()

我想this.a不应该是这个规模(或者你改变了主意(。解决方法是将其结构更改为

this.a = this.rp.addition(this.ra); 
相关文章: