为什么对象点符号不能用于未知类型的对象? (TypeError:undefined不是对象)

时间:2015-11-12 03:17:26

标签: javascript oop methods typeerror

我正在编写一个带有粒子的物理模拟器,我需要的一个函数是other函数,它允许粒子找到它与另一个名为other.pos[i]的输入粒子的距离。当我运行此脚本时,错误日志显示:

  

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

错误似乎在pos中,但我不知道如何找到other对象的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)); 变量。

IMongoQueryable.Where

2 个答案:

答案 0 :(得分:1)

for (var r in range) {

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

答案 1 :(得分:0)

我不明白为什么你首先要做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"