2

I want to call iteration from itself, what would be the best way to do it?

function Items(names) {
    this.name = "Bo";
    this.iteration();
}

Items.prototype.iteration = function(){
    console.log("calling iteration");
    setTimeout(function(){
        this.iteration(); // <----------- Wrong 
        this.prototype.iteration(); // <----------- Wrong 
        // right way <-------------- undefined
    } ,1000 );
}

Thought these would work just like this.name would.

user3800799
  • 534
  • 1
  • 5
  • 18

3 Answers3

2

You have to bind your function to the current context (=> this), for example with the bind function:

function Items(names) {
    this.name = "Bo";
    this.iteration();
}

Items.prototype.iteration = function(){
    console.log("calling iteration");
    setTimeout(this.iteration.bind(this), 1000);
}
friedi
  • 4,350
  • 1
  • 13
  • 19
1

One solution would be to you use Function.prototype.bind to bind callback function to correct context:

Items.prototype.iteration = function() {
    console.log("calling iteration");
    setTimeout(function() {
        this.iteration();
        this.prototype.iteration();
    }.bind(this), 1000);
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

Preserve the object in a variable, then call iteration

function Items(names) {
  this.iteration();
}

Items.prototype.iteration = function() {
  var self = this;
  console.log("calling iteration");
  setTimeout(function() {
    self.iteration();
  }, 1000);
}

var item = new Items();
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53