简体   繁体   中英

Modifying the parameter of a looped function in Javascript

I'm having issues with getting this JSFiddle to work:

http://jsfiddle.net/y45jN/

var mainFunction = function() {
  this.text;
}

mainFunction.prototype.start = function(printText) {

  this.text = printText;

  var func = function() {
    document.getElementById('test').innerHTML += this.text + '<br/>';
  };

  setInterval(func,1000);

}

mainFunction.prototype.updateText = function(printText) {

  this.text = printText;

}

var test = new mainFunction();
test.start('hello');

setTimeout(function(){
  test.updateText('bye');
},5000);

What I want to do is for the first 5 seconds print hello and after 5 seconds print bye.

I'm unsure on how I can make the function (func) know that the this.text parameter of the class has changed.

You've messed up the context here. Cache this in some variable and use it inside an interval (or use bind ):

    this.text = printText;
    var self = this;

    var func = function() {
        document.getElementById('test').innerHTML += self.text + '<br/>';
    };

Then, simply modify the instance's property text :

setTimeout(function(){
    test.text = 'bye';
},5000);

Fiddle

Solution using bind method:

setInterval(func.bind(this),1000);

http://jsfiddle.net/y45jN/5/

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