1

Please bear with me. I'm working on the following loop and I'm trying to figure out why foo.count is never incremented and displays 0. I would like to rewrite the example so that foo.count is properly incremented. I know I'm overlooking something. Any suggestions? Thanks

function foo(num) {
  console.log("foo: " + num);
  this.count++;
}
foo.count = 0;

var i;
for (i = 0; i < 10; i++) {
  if (i > 5) {
    foo(i);
  }
}
// foo: 6 
// foo: 7 
// foo: 8 
// foo: 9 
console.log(foo.count); // Still 0!
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Spanky
  • 699
  • 2
  • 11
  • 38
  • 3
    in the context of the code you posted, this.count is not foo.count - you need to learn how `this` works - in this example, if you always use `foo.count` you'll be golden – Jaromanda X Oct 18 '16 at 23:18
  • Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Mike Cluck Oct 18 '16 at 23:20
  • @Jaromanda X Thanks for the input! I overlooked the use of "this". – Spanky Oct 19 '16 at 00:31

3 Answers3

3

As mentioned by Jaromanda, you're utilizing this incorrectly. In this scenario, you need to be careful where you use it. Try replacing this.count++ with foo.count++

function foo(num) {
  console.log("foo: " + num);
  foo.count++;
}
foo.count = 0;

var i;
for (i = 0; i < 10; i++) {
  if (i > 5) {
    foo(i);
  }
}
// foo: 6 
// foo: 7 
// foo: 8 
// foo: 9 
console.log(foo.count); // Still 0!

Note that using this references the object it is contained within, not the function in is contained within, as it appears you mistakenly have taken it for. When referencing the object that is currently contained, it is necessary to use the 'this' operator, not only for clarity, but also to avoid potential ambiguity.

Shane Duffy
  • 1,117
  • 8
  • 18
3

Based on what you've written, if you were to console.log(this) inside your foo() function, you'd see that it prints the window object.

function foo() {
  console.log(this); // prints "window" and/or attributes
}
foo();

You've created a count variable on both the window and bolted onto the side of the foo() function. However, being attached TO the function isn't the same thing as being inside the function's scope.

So that foo.count variable never gets incremented since it's different from this.count (which is on window).

Soviut
  • 88,194
  • 49
  • 192
  • 260
0
//"this" is window object. In the following code, I have replaced "foo.count" by "count".
  function foo ( num ) { 
        console.log ( "foo: " + num );
        this.count++; 
        }

            count = 0; 
            var i; 
            for ( i = 0 ; i < 10 ; i ++ ) { 
            if ( i > 5 ) { 
            foo ( i ); 
            } 
        } 
        // foo: 6 
        // foo: 7 
        // foo: 8 
        // foo: 9 
        console.log ( foo.count ); // Still 0!
Nandan Bhat
  • 1,573
  • 2
  • 9
  • 21