Search code examples
javascriptthisprototype

Undefined DOM element in Prototype Class


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

Solution

  • 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.