JavaScript对象未实例化

时间:2019-11-22 23:36:16

标签: javascript oop p5.js

我有一个类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...
}

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

1 个答案:

答案 0 :(得分:2)

问题在于您正在创建全局变量>name1 atgcatgcatgcatgcatgcat >name2 tgcatgcatgcatgcat >name3 gcatgcatgcatgcatgcat >namen.... ,并使用它代替self。所有实例都在访问同一个全局变量,该变量包含来自创建的最后一个对象的this的值。

this的回调函数中,您需要一种引用原始对象的方法,因此需要在此处绑定局部变量tick(),而不是使用全局变量。参见How to access the correct `this` inside a callback?

self
相关问题