0

I'm having trouble making a recursive call in this prototype method. The console prints:

count 1 (index):30
Uncaught ReferenceError: count is not defined 

Instead, I need it to print:

count 1 (index):30
count 2 (index):30

...

var MyClass, mc;

MyClass = (function() {
  function MyClass() {
    this.count = 1;
  }

  MyClass.prototype.method = function() {
    console.log("count", this.count);
    this.count++;
    if (count === 2) {
      method();
    }
  };

  return MyClass;

})();

mc = new MyClass();

mc.method();

http://jsfiddle.net/audfmotf/

jcalfee314
  • 4,642
  • 8
  • 43
  • 75
  • More on prototype and constructor functions here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Oct 16 '14 at 02:55

2 Answers2

1

You forgot a couple of this inside method.

MyClass.prototype.method = function() {
  console.log("count", this.count);
  this.count++;
  if (this.count === 2) {
    this.method();
  }
};
berrberr
  • 1,914
  • 11
  • 16
0

count is not the same as this.count. Your condition checks for an undefined variable, instead of:

if (this.count === 2) {
      this.method();
    }
Shomz
  • 37,421
  • 4
  • 57
  • 85