【问题标题】:Accessing array from objects method within array从数组中的对象方法访问数组
【发布时间】:2019-09-10 09:56:08
【问题描述】:

我已经研究过这个问题,但找不到答案。我是 JavaScript 数组和方法范围的新手。

我有一个包含圆形对象的圆形数组。这有一个更新方法,最终让它自己绘制到画布上并移动

问题是 Circles 需要能够访问其 circles 数组中其他 Circles 的位置,以查看它们是否发生碰撞。

但是当我使用 Circles 方法时,他们无法识别他们的持有数组 - circles:

let circles;

function init() {
    circles = [];

for (i = 0; i < 5; i++) {
    let dy = (Math.random() - 0.5) * 8;
    let radius = Math.random() * 30;
    let color = colors[Math.floor(Math.random() * colors.length)];
    let x = Math.random() * (innerWidth - radius * 2) + radius;
    let dx = (Math.random() - 0.5) * 8;
    let y = Math.random() * (innerHeight - radius * 2) + radius;

    circles.push(new Circle(x, y, dx, dy, radius, color));
}
}

function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, innerWidth, innerHeight);
    circles.forEach(circle => {
        circle.update();
    });
}

function Circle(x, y, dy, dx, radius, color) {
    this.x = x;
    this.y = y;
    this.dy = dy;
    this.dx = dx;
    this.radius = radius;
this.color = color;

this.update = function (circles) {
    for (i = 0; i < circles.length; i++) {
        if (this === circles[i]) {
            continue;
        }
        if (getDistance(this.x, this.y, circles[i].x, circles[i].y) - radius * 2 < 0) {
            console.log('TOUCH')
        }
    }
    this.draw();
}

this.draw = function () {
    c.beginPath();
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    // c.strokeStyle = 'black';
    c.fillStyle = this.color;
    c.fill();
    c.closePath();
}
}

这个函数导致错误:

未捕获的类型错误:无法读取未定义的属性“长度”

因为它无法识别 circles 数组。

如何让我的对象方法访问对象所在的数组?

【问题讨论】:

  • 从this.update = function (circles) { 中删除circles。它为该局部函数范围定义了一个新的变量圆,而不是使用原始的。此外,出于范围界定的原因,您可能想要使用 var 而不是 let,但不是 100% 在我的头上。

标签: javascript arrays object canvas methods


【解决方案1】:

Circle 上的 update 方法需要传递 circles 数组,但您没有传递任何内容:

function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, innerWidth, innerHeight);
    circles.forEach(circle => {
        circle.update(circles); // <--- HERE
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2012-02-27
    • 2019-03-22
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多