属性 两个原型函数中的值不相同

Property values inside two prototype functions are not the same

我在构造函数中初始化我的 this.interval=null,然后我想在 prototype.blink 中更改最后一个,但是当我在 prototype.stopBlink() 中对其进行控制台时,它给出了 null值

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);
}

正如 sjahan 为您所写的那样,在您的 setTimeout 函数中,this 关键字不再指向 class 的实例,而是指向 window 对象。

改为使用箭头函数,更改

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

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

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

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

  setTimeout(() => {
    console.log(this.interval);

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

这是一个简化为主要活动部件的工作示例。它在 stopBlinksetTimeout 中使用箭头函数。这很重要,因为您希望从词法上捕获 this 的值,而不是从超时调用中捕获。不清楚为什么要在 blink() 中使用立即返回的函数,但我把它留了下来:

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)