javascript - 原型(prototype)方法返回 "undefined"

标签 javascript object prototype paperjs

在运行对象方法时遇到了一些麻烦,而且我对 OOP 还很陌生。我有以下构造函数类:

function Blob(c, maxRadius, points, v) {

    this.vector = v;
    this.maxVector = 5;
    this.center = c;


    this.path = new Path();
    this.path.closed = true;
    for (var i = 0; i < points; i++) {
        var delta = new Point({
            length: (maxRadius * 0.5) + (Math.random() * maxRadius * 0.5),
            angle: (360 / points) * i
        });
        this.path.add(center + delta);
    }
    this.path.smooth();
    this.path.fillColor = colors[i % 3];
};

然后我想为每个“blob”对象制作以下方法的原型(prototype)

Blob.prototype = {
    iterate: function() {
        this.checkBorders();
        if (this.vector.length > this.maxVector)
            this.vector.length = this.maxVector
        this.center += this.vector;

    },
    checkBorders: function() {
        var size = view.size;
        if (this.center.x < -this.radius)
            this.center.x = size.width + this.radius;
        if (this.center.x > size.width + this.radius)
            this.center.x = -this.radius;
        if (this.center.y < -this.radius)
            this.center.y = size.height + this.radius;
        if (this.center.y > size.height + this.radius)
            this.center.y = -this.radius;
    }
};

然后我在一个新函数中调用构造函数类,该函数又将所需的参数传递给构造函数类:

function createPaths() {
    var radiusDelta = values.maxRadius - values.minRadius;
    var pointsDelta = values.maxPoints - values.minPoints;

    for (var i = 0; i < values.paths; i++) {
        var radius = values.minRadius + Math.random() * radiusDelta;
        var points = values.minPoints + Math.floor(Math.random() * pointsDelta);
        var center = view.size * Point.random();
        var vector = new Point({
            angle: 360 * Math.random(),
            length: Math.random() * 10
        });

        blobs.push(Blob(center, radius, points, vector));
    };
}

但是当我尝试从一个函数中访问它时:

function onFrame() {
    for (var i = 0; i < blobs.length - 1; i++) {
        blobs[i].iterate();
    }
}

返回

“Uncaught TypeError: Cannot read property 'iterate' of undefined”,在我看来原型(prototype)失败了?当我从 onFrame() 中控制“blobs[i]”时,它返回我希望找到的对象数组,因此类构造函数似乎没有任何问题......非常感谢任何帮助!

最佳答案

更改数组填充以使用 new 以便创建不同的对象

blobs.push(new Blob(center, radius, points, vector));

您当前的代码只是执行 Blob 函数,该函数不返回任何内容 (undefined)

关于javascript - 原型(prototype)方法返回 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27047222/

相关文章:

javascript - 有人可以帮助我了解网络应用程序中网络客户端的 Google Cloud Endpoints 的作用吗?

javascript - 如何用Realm来组织React Native项目文件?

javascript - 字符串同时包含 ' & "

javascript - 如果第二个对象中不存在,则填充对象中的选择框

javascript - 如何确定变量是否是 javascript 中的错误?

javascript - 将 js 文件从原型(prototype)迁移到 jQuery 不起作用

javascript - 如何在javascript中定义嵌套数组?

javascript - 如何仅将对象属性子集的值复制到 TypeScript 中的另一个现有对象

javascript - 将对象的方法作为回调传递的最佳或最常见的方法是什么?

javascript - 使用 array.prototype.push 与 array.push