大家好,我有以下代码
POINT = function () {
that = {};
that.x = 0; that.y = 0;
that.setPoint = function (x, y) {
that.x = x;
that.y = y;
};
that.toString = function () {
return that.x + ',' + that.y + ' ';
};
return that;
};
PEN = function () {
var that = {};
var points = [];
var buffer_size = 5, head = -1, length = 0;
// Init buffer
for (var i = 0; i < buffer_size; i++) {
points.push(POINT());
}
that.addPoint = function (x, y) {
head = (head + 1) % buffer_size;
points[head].setPoint(x, y);
if (length < buffer_size) {length++;}
};
that.toString = function (path) {
var d = '';
for (var i = 0; i < length; i++) {
var index = (head - i) < 0 ? buffer_size + (head - i) : (head - i);
d += points[index].toString();
}
return d;
};
return that;
};
// Initialization
var i = 0, pen = PEN();
for (var i = 0; i < 10; i++) {
pen.addPoint(i + 1, i + 1);
}
alert(pen.toString()); // RESULT 10,10 10,10 10,10 10,10 10,10
points
数组中填充了正确的pen
对象,但函数setPoint
始终指向数组pen
中的最后一个对象points
。
注意:我想要直接访问x
和y
协调,因此我没有使用 var 声明x
和y
作为“本地”变量。
在这里可以找到带有示例的小提琴:http: //jsfiddle.net/DNVjy/2/