JavaScript 对象未实例化

JavaScript Objects not instantiating

我有一个 class 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
};

classdynObj如下:

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...
}

为什么实例会相互影响? (如果需要更多上下文,可以为此提供 link)

问题是您正在创建一个全局变量 self,并使用它而不是 this。所有实例都在访问同一个全局变量,该变量包含来自最后创建的对象的 this 的值。

tick()中的回调函数中,您需要一种方法来引用原始对象,因此您需要在那里绑定一个局部变量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...
}