在运行对象方法时遇到了一些麻烦,而且我对 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/