1

My goal is to have a button that when clicked, it will create an object that blinks by using toggle and set timeout and then appending the object onto the Html. However, I'm getting a "Cannot read property 'toggle' of undefined" error message in my Javascript code.

JS to create the object

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)
}
Community
  • 1
  • 1
Leo Tsang
  • 27
  • 4
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – FZs Jun 18 '20 at 14:39
  • Just tried this and yes it works now. Thank you so much! – Leo Tsang Jun 18 '20 at 23:30

1 Answers1

1

This is standard problem that arises when this loses context.

Try using bind, link this:

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

See this question and answers for more info.

TeWu
  • 5,928
  • 2
  • 22
  • 36