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

时间:2019-06-26 15:40:45

标签: javascript babylonjs

我在构造函数中初始化this.interval = null,然后我想在prototype.blink中更改最后一个,但是当我在prototype.stopBlink()中进行操作时,它会给出空值

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

2 个答案:

答案 0 :(得分:1)

就像sjahan为您编写的那样,在setTimeout函数中,this关键字不再指向类的实例,而是指向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);
}

答案 1 :(得分:1)

这是一个简化为主要运动部件的工作示例。它在stopBlink的{​​{1}}中使用箭头功能。这很重要,因为您想以词法捕获setTimeout的值,而不是从超时调用中捕获。目前尚不清楚为什么在this中使用立即返回的函数,但我留了它:

blink()