Search code examples
javascriptbabylonjs

Property values inside two prototype functions are not the same


I initialize my this.interval=null in constructor, and then I want to change this last one in prototype.blink, but when I console it inside prototype.stopBlink() it gives null value

function Mesh(name, material) {
  this._name = name;
  this._material = material;
  this.interval = null;
}

Mesh.prototype.blink = function(obj, delay, box) {
  this.interval = (() => {
    var Toggle = true
    return setInterval(() => {
      if (Toggle)
        changeMaterial(obj, box);
      else {
        changeMaterial(obj, this._material);
      }

      Toggle = !Toggle;
    }, delay);
  })();

  console.log(this.interval);
}

Mesh.prototype.stopBlink = function(obj, duration) {

  setTimeout(function() {
    console.log(this.interval);

    clearInterval(this.interval);
  }, duration);
}

Solution

  • Here's a working example reduced to the main moving parts. It uses an arrow function inside stopBlink's setTimeout. This is important because you want to capture the value of this lexically, not from the timeout call. It's not clear why you are using the immediately returned function inside blink(), but I left it:

    function Mesh(name) {
      this._name = name;
      this.interval = null;
    }
    
    Mesh.prototype.blink = function(delay) {
      var Toggle = false
      this.interval = (() => {
        return setInterval(() => {
          console.log(this._name, " blinking ", "Toggle", Toggle)
          Toggle = !Toggle;
        }, delay);
      })();
      console.log("interval in blink:", this.interval)
    
    }
    
    Mesh.prototype.stopBlink = function(duration) {
    
      setTimeout(() => {
        console.log("interval in stop: ", this.interval)
        clearInterval(this.interval);
      }, duration);
    }
    
    let m = new Mesh("mesh")
    m.blink(200)
    m.stopBlink(1000)