我有一个类 dynObj
,但它的单独实例似乎采用了最近定义的实例的值。
draw() {
tmov1 = new dynObj(args...); //Displays as a white ball on webpage, as intended
tmov2 = new dynObj(different args...); //Seemingly overwrites the properties of tmov1
objects.push(tmov1, tmov2)
for (var i in objects) {
objects[i].dostuff() //Normally causes the object to display as intended,
}; //but will only ever display one
};
类dynObj如下:
class baseObj {
constructor(position, dimentions, properties) {
this.pos = createVector(position.x,position.y) || null;
this.shape = properties.shape
if (this.shape == "ellipse") {
this.dim = dimentions || {diam:0}
} else if (this.shape == "quadrilateral") {
this.dim = dimentions || { x: 0, y: 0 };
}
};
};
class dynObj extends baseObj {
constructor(position, dimentions, suvat, properties) {
super(position, dimentions, properties);
self = this
self.type = 'dynamic'
self.properties = properties
//more definitions with self.x = someval
};
getDistance(a,b){
if (a == undefined || b == undefined) return false;
var dist = p5.Vector.sub(b,a)
//console.log(dist)
return dist
};
tick(ticksize) {
self.assignLastTick(function(lasttick){
self.lasttick = lasttick
self.time = self.time + ticksize
self.updateSuvat(ticksize)
})
};
//assorted methods...
}
为什么实例会相互影响? (如果需要更多上下文,可以提供指向此操作的链接)
最佳答案
问题是您正在创建全局变量 self
,并使用它而不是 this
。所有实例都在访问同一个全局变量,该变量包含来自最后创建的对象的 this
的值。
在tick()
中的回调函数中,需要一种方法来引用原始对象,所以需要在那里绑定(bind)一个局部变量self
,而不是使用一个全局变量。参见 How to access the correct `this` inside a callback?
class dynObj extends baseObj {
constructor(position, dimentions, suvat, properties) {
super(position, dimentions, properties);
this.type = 'dynamic'
this.properties = properties
//more definitions with this.x = someval
};
getDistance(a,b){
if (a == undefined || b == undefined) return false;
var dist = p5.Vector.sub(b,a)
//console.log(dist)
return dist
};
tick(ticksize) {
let self = this;
this.assignLastTick(function(lasttick){
self.lasttick = lasttick
self.time = self.time + ticksize
self.updateSuvat(ticksize)
})
};
//assorted methods...
}
关于JavaScript 对象未实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003138/