Неопределенный элемент DOM в классе прототипа - PullRequest
1 голос
/ 18 июня 2020

Моя цель - иметь кнопку, при нажатии на которую она будет создавать мигающий объект с помощью переключателя и установки тайм-аута, а затем добавление объекта в Html. Однако в моем коде Javascript появляется сообщение об ошибке «Не удается прочитать свойство 'toggle' of undefined».

JS для создания объекта

var MakeSquare = function (top, left, time) {
    this.time = time;
    this.$node = $('<span class="square"></span>');
    this.setPosition(top, left);
    this.repeat();
}

// this function will set the position of the <span> on the webpage
MakeSquare.prototype.setPosition = function (top, left) {
  var styleSettings = {
    top: top,
    left: left
  };
  this.$node.css(styleSettings);
};

// this function will toggle the <span> off, and invoke the repeat function to turn it back on again, and so forth.
MakeSquare.prototype.step = function() {
  this.$node.toggle();
  this.repeat();
}

MakeSquare.prototype.repeat = function () {
  setTimeout(this.step, this.time)
}

1 Ответ

1 голос
/ 18 июня 2020

Это стандартная проблема, которая возникает, когда this теряет контекст.

Попробуйте использовать bind, свяжите это:

MakeSquare.prototype.repeat = function () {
  setTimeout(this.step.bind(this), this.time)
}

См. этот вопрос и ответы для получения дополнительной информации.

...