运行对象方法时遇到一些麻烦,对于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];
};
然后,我想将以下方法原型化为每个&#34; blob&#34;对象
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();
}
}
它返回
&#34;未捕获的TypeError:无法读取属性&#39;迭代&#39;未定义&#34;,在我看来,原型失败了吗?当我安慰&#34; blobs [i]&#34;从onFrame()内部返回我期望找到的对象数组,因此它看起来不像是类构造函数的任何问题......任何帮助都非常感谢!
答案 0 :(得分:2)
更改数组填充以使用new,以便创建不同的对象
blobs.push(new Blob(center, radius, points, vector));
您当前的代码只执行Blob
函数,该函数不返回任何内容( undefined
)
答案 1 :(得分:0)
添加到原型而不是重新定义它:
Blob.prototype.checkBorders = function() { ... };
Blob.prototype.iterate = function() { ... };
并且不要忘记new
关键字新实例化新的blob对象。