简体   繁体   English

在JavaScript中修改循环函数的参数

[英]Modifying the parameter of a looped function in Javascript

I'm having issues with getting this JSFiddle to work: 我在使此JSFiddle正常工作时遇到问题:

http://jsfiddle.net/y45jN/ 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. 我想做的是在开始的5秒内打个招呼,然后在5秒后打个再见。

I'm unsure on how I can make the function (func) know that the this.text parameter of the class has changed. 我不确定如何使函数(func)知道该类的this.text参数已更改。

You've messed up the context here. 您已经弄乱了这里的上下文。 Cache this in some variable and use it inside an interval (or use bind ): 高速缓存this在一些变量,并使用它的时间间隔内(或使用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 : 然后,只需修改实例的属性text

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

Fiddle 小提琴

Solution using bind method: 使用绑定方法的解决方案:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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