为什么对象点表示法不适用于未知类型的对象?(类型错误:未定义不是对象)



我正在写一个粒子物理模拟器,我需要的函数之一是distanceTo函数,它允许粒子找出它与另一个输入粒子other的距离。当我运行这个脚本时,错误日志显示:

TypeError:undefined不是第11行上的对象。

错误似乎在other.pos[i]中,但我不知道如何找到other对象的pos变量。

1     function Particle(mass, radius, pos, vel) {
2          this.mass = mass;
3          this.radius = radius;
4          this.pos = pos;
5          this.vel = vel;
6     
7          this.distanceTo = function(other) {
8              var k = 0;
9              var l = this.pos.length;
10             for (var i = 0; i < l; ++i) {
11                 k += Math.pow(this.pos[i] - other.pos[i], 2);
12             }
13             return Math.sqrt(k);
14         }
15           
16         this.scan = function(range, limit) {
17             for (var r in range) {
18                 if (this.distanceTo(r) <= limit){
19                     return "within the limit";
20                 } else {
21                     return "outside the limit";
22                 }
23             }
24         }
25     }
26
27     var p1 = new Particle(1, 0.1, [0, 0], [0, 0]);
28     var p2 = new Particle(1, 0.1, [10, -2], [0, 0]);
29
30     console.log(p1.distanceTo(p2));
31     console.log(p1.scan([p2], 10));

在中

for (var r in range) {

r将是0——range数组的第一个也是唯一的索引。则this.distanceTo(r)将失败。

我不明白为什么首先要执行for...in,但如果我删除循环并将obj作为两个函数的参数传递,似乎可以正常工作。

检查这是否适用于您:

function Particle(mass, radius, pos, vel) {
  this.mass = mass;
  this.radius = radius;
  this.pos = pos;
  this.vel = vel;
  this.distanceTo = function(other) {
    var k = 0;
    var l = this.pos.length;
    for (var i = 0; i < l; ++i) {
      k += Math.pow(this.pos[i] - other.pos[i], 2);
    }
    return Math.sqrt(k);
  };
  this.scan = function(range, limit) {
    if (this.distanceTo(range) <= limit){
        return "within the limit";
      } else {
        return "outside the limit";
      }
  };
}
var p1 = new Particle(1, 0.1, [0, 0], [0, 0]);
var p2 = new Particle(1, 0.1, [10, -2], [0, 0]);
console.log(p1.distanceTo(p2)); // 10.198039027185569
console.log(p1.scan(p2, 10)); // "outside the limit"