简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM